2011-08-10 2 views
2

내 미리 채워진 데이터베이스를 내 장치에로드하려고 시도한 적이 있습니다. 필자는 시뮬레이터 디렉터리에서 데이터베이스를 복사하여 응용 프로그램 폴더에 복사하려고 시도했지만 작동하지 않아서 날씨가 NSFetchedResultsController가 제대로 가져오고 있는지 궁금합니다.이 CoreData NSFetchedResults 및 NSPersistentStore 함수를 사용하는 올바른 방법입니까?

- (NSFetchedResultsController *)fetchedResultsController { 

    if (fetchedResultsController_ != nil) { 
     return fetchedResultsController_; 
    } 

    CoreDataMelakaAppDelegate *appDelegate = (CoreDataMelakaAppDelegate *)[[UIApplication sharedApplication] delegate]; 
    NSManagedObjectContext *context = [appDelegate managedObjectContext]; 
    // Create the fetch request for the entity. 
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
    // Edit the entity name as appropriate. 
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"WhereTo" inManagedObjectContext:context]; 
    [fetchRequest setEntity:entity]; 

    // Set the batch size to a suitable number. 
    // [fetchRequest setFetchBatchSize:20]; 

    // Edit the sort key as appropriate. 
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO]; 
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; 

    [fetchRequest setSortDescriptors:sortDescriptors]; 

    // Edit the section name key path and cache name if appropriate. 
    // nil for section name key path means "no sections". 
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"]; 
    aFetchedResultsController.delegate = self; 
    self.fetchedResultsController = aFetchedResultsController; 

    [aFetchedResultsController release]; 
    [fetchRequest release]; 
    [sortDescriptor release]; 
    [sortDescriptors release]; 

    NSError *error = nil; 
    if (![fetchedResultsController_ performFetch:&error]) { 
     /* 
     Replace this implementation with code to handle the error appropriately. 

     abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. 
     */ 
     NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
     abort(); 
    } 

    return fetchedResultsController_; 
}  

내가이 함께 persistentStore를 교체했습니다, 지금은 데이터베이스 또는 시뮬레이터에서 응용 프로그램을 삭제하는 방법을 지금까지, 내가 첫 번째를 설치,이 데이터를 표시

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 

    if (persistentStoreCoordinator_ != nil) { 
     return persistentStoreCoordinator_; 
    } 

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataMelaka.sqlite"]; 

    NSError *error = nil; 
    persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 
    if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { 
     /* 
     Replace this implementation with code to handle the error appropriately. 

     abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. 

     Typical reasons for an error here include: 
     * The persistent store is not accessible; 
     * The schema for the persistent store is incompatible with current managed object model. 
     Check the error message to determine what the actual problem was. 


     If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory. 

     If you encounter schema incompatibility errors during development, you can reduce their frequency by: 
     * Simply deleting the existing store: 
     [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil] 

     * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 
     [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; 

     Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details. 

     */ 
     NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
     abort(); 
    }  

    return persistentStoreCoordinator_; 
} 

을 PersistenStore 나는이 방법을 시도했다.

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 

    if (persistentStoreCoordinator_ != nil) { 
     return persistentStoreCoordinator_; 
    } 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"CoreDataMelaka.sqlite"]; 

    NSString *storePath = [[NSBundle mainBundle] pathForResource:@"CoreDataMelaka" ofType:@"sqlite"]; 


    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataMelaka.sqlite"]; 

    NSLog(@"store URL %@", storeURL); 

    // Put down default db if it doesn't already exist 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    if (![fileManager fileExistsAtPath:writableDBPath]) { 
     NSLog(@"proceed"); 
     NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"CoreDataMelaka" ofType:@"sqlite"]; 
     NSLog(@"doesnt exist"); 
     NSLog(@"defalultStorePath %@", defaultStorePath); 


     if (defaultStorePath) { 
      [fileManager copyItemAtPath:defaultStorePath toPath:writableDBPath error:NULL]; 
      NSLog(@"storePath= %@", storePath); 
     } 
    }  

    NSError *error = nil; 
    persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 
    if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { 

     NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
     abort(); 
    }  

    return persistentStoreCoordinator_; 
} 
+0

미리 채워진 데이터베이스가 CoreData로 생성 되었습니까? 아니면 직접 만들었습니까? –

+0

나는 시뮬레이터를 사용하여 코어 데이터를 사용하여 미리 채워진 데이터베이스를 만든다. 시뮬레이터에 저장되어 있지만 해당 특정 데이터베이스를 복사하여 응용 프로그램 폴더에 붙여 넣으면 시뮬레이터에 비어있는 새 데이터베이스가 새로 만들어져 응용 프로그램 폴더의 1 대신에 읽습니다. – Harvin

답변

0

NSFetchedResultsController는 표준 자동 생성 코드와 유사합니다. 올바르게 가져 오는 것이 좋지만 코드를 100 % 확실하게 알아야합니다.

문제는 데이터베이스를 찾는 것과 관련이 있다고 생각합니다. 문서 디렉토리에 넣으시겠습니까? 나는 당신이 데이터베이스를 Xcode로 복사했다고 가정하고 당신의 데이터베이스를 당신의 app으로 복사하고있다. 이 경우 데이터베이스가 Documents 디렉토리에 저장되지 않습니다. Xcode에서 Organizer의 Device 섹션을 사용하여 앱 파일을 다운로드 할 수 있습니다. 데이터베이스가 기본 번들로 복사되고 거기에서 압축을 풀어야합니다.

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 

    if (__persistentStoreCoordinator != nil) 
     return __persistentStoreCoordinator; 

    NSError * error = nil; 
    NSURL * storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Store.sqlite"]; 
    NSFileManager * fileManager = [NSFileManager new]; 

    // !!!: Be sure to create a new default database if the MOM file is ever changed. 

    // If there is no previous database, then a default one is used. 
    if (![fileManager fileExistsAtPath:storePath]) { 

     NSURL * defaultStoreURL = [[NSBundle mainBundle] URLForResource:@"DefaultStore.sqlite" 
                  withExtension:nil]; 

     // Copies the default database from the main bundle to the documents directory. 
     [fileManager copyItemAtURL:defaultStoreURL 
          toURL:storeURL 
          error:&error]; 

     if (error) { 

      // Handle error here. 

      // Resets the error. 
      error = nil; 
     } 
    } 

    [fileManager release]; 

    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 

    [__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType 
              configuration:nil 
                URL:storeURL 
               options:nil 
                error:&error]; 
    if (error) { 

     // Handle error here. 

     abort(); 
    }  

    return __persistentStoreCoordinator; 
} 

RBCoreDataAdditions 체크 아웃, 이것과 다른 코어 데이터의 편의를 찾으려면 : 여기에 그냥 않는 일부 코드입니다.

+0

예, 데이터베이스를 가져 오는 중입니다. 사용자/라이브러리/응용 프로그램 지원/iphone 시뮬레이터/4.3.2/응용 프로그램/<일부 정수>/Documents .. 장치 부분을 사용하여 파일 다운로드 부분을 이해하지 못합니다. 주최자 섹션에서 수동으로 디렉토리에서 다운로드 할 수 있습니까? 내가 이것을 앱 스토어에 올리면 데이터베이스가 의식을 따르지 않을까? – Harvin

+0

시뮬레이터의 문서에서 복사 할 수 있지만 Xcode를 통해 응용 프로그램에 복사하면 주 번들로 이동합니다. 장치에서 파일을 다운로드하려면 Organizer를 열고 장치 탭을 선택하고 장치 아래의 응용 프로그램을 선택하고 응용 프로그램을 선택한 다음 다운로드를 선택하십시오. Xcode 4를 사용하고 있습니다. 파일을 다운로드하면 기본 데이터베이스가 기본 번들에 있음을 확인해야합니다. 데이터베이스를 메인 번들에 넣으면 앱 스토어에 업로드됩니다. 이것이 원하는 것이 아니면 보관하기 전에 제거해야합니다. – rbrown

+0

문서 디렉토리에 데이터베이스가 있지만 핵심 데이터가 생성 한 빈 데이터베이스 여야합니다. 이것을 열고 몇 가지 쿼리를 실행하여이를 확인할 수 있습니다. – rbrown

관련 문제