2012-02-18 3 views
0

API에서 정보를 빼내고 데이터베이스를 채우는 것과 같은 핵심 데이터 데이터베이스를 하나의 응용 프로그램에서 만들었습니다.사전로드 된 핵심 데이터 데이터베이스가 작동하지 않습니다.

이제 다른 앱에서 사용하고 싶습니다.

.xcdatamodeld 파일과 NSManagedObject 클래스를 복사했습니다.

코어 데이터 프레임 워크를 추가하고 가져 왔습니다.

.sqlite 파일을 기본 데이터베이스로 새 응용 프로그램의 리소스에 복사했습니다.

기본 데이터베이스를 Documents 디렉토리로 복사하고 열어서 쿼리를 수행 할 예정인 다음 코드를 사용하고 있습니다.

오류 메시지가 표시되지 않고 앱이 충돌하고 어디에서 잘못 되었습니까?

saveToURL을 사용하여 여기에 데이터베이스를 만들었다면 파일 이름이 persistentStore가 될 것입니다. 아래의 Trailer.sqlite는 관련성이 있습니까?

감사

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 


// Get URL -> "<Documents Directory>/<TrailerDB>" 
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; 

url = [url URLByAppendingPathComponent:@"TrailerDB"]; 

UIManagedDocument *doc = [[UIManagedDocument alloc] initWithFileURL:url]; 

// Copy out default db to documents directory if it doesn't already exist 
NSFileManager *fileManager = [NSFileManager defaultManager]; 

if (![fileManager fileExistsAtPath:[url path]]) { 
    NSString *defaultDB = [[NSBundle mainBundle] 
            pathForResource:@"trailerdatabase" ofType:@"sqlite"]; 
    if (defaultDB) { 

     [fileManager copyItemAtPath:defaultDB toPath:[url path] error:NULL]; 

    } 
} 

if (doc.documentState == UIDocumentStateClosed) { 

    // exists on disk, but we need to open it 
    [doc openWithCompletionHandler:^(BOOL success) 
    { 

     if (success) [self useDatabase:doc]; 

     if (!success) NSLog(@"couldn’t open document at %@", url); 


    }]; 

} else if (doc.documentState == UIDocumentStateNormal) 
{ 
    [self useDatabase:doc]; 
} 

} 
+0

디버거 각 라인을 통해 단계 및 – jackslash

+0

openWithCompletionHandler가 호출되는 충돌이 발생하지만, 심지어 충돌 ... – Alan

답변

1

필자는 또 다른 모습을했고, 나는 당신이 무슨 일을하는지 모르겠지만 다음이 코드는 내가 그 질문에 대답 할 않는 것입니다. 작업 데이터베이스가 있는지 확인하고 응용 프로그램 번들에서 해당 위치로 이동 한 다음로드하려면 계속 진행합니다. 나는 그들이 도움이 될지도 모른다라고 생각하는 것에 따라 애플 템플릿으로부터 주식 설명을 남겼다.

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator 
{ 
    if (__persistentStoreCoordinator != nil) 
    { 
     return __persistentStoreCoordinator; 
    } 

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

    NSError *error = nil; 

    if (![[NSFileManager defaultManager] fileExistsAtPath:[[self applicationDocumentsDirectoryString] stringByAppendingPathComponent: @"workingDataBase.sqlite"]]){ 
     //database not detected 
     NSLog(@"database not detected"); 
     NSURL * defaultDatabase = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"DefaultData" ofType:@"sqlite"]]; 
     NSError * error; 
     if (![[NSFileManager defaultManager] copyItemAtURL:defaultDatabase toURL:storeURL error:&error]){ 
      // Handle Error somehow! 
      NSLog(@"copy file error, %@", [error description]); 
     } 
    } 

    __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; 
} 
+0

감사 전에 다시 완료 블록을하지 않습니다,하지만 난 봤는데 어느 쪽 참조 지금까지는이 솔루션이 필요하다고 생각하는 앱 델리게이트를 사용하지 않아도되는 ios5에 익숙하지 않은 UIManagedDocument 클래스를 사용합니다. [self managedObjectModel]. 앱 델리게이트에 여분의 코드를 포함 할 필요가없는 것 같아 "코어 데이터 사용"을 체크 할 수있는 옵션조차 없습니다. – Alan

+0

공정합니다. 이 코드는 MOC를 만들면 어디든지 갈 수 있습니다. 그들은 여러 대의 MOC를 만드는 더 쉬운 장소 였기 때문에 앱 위임에 보관했습니다. 아직 UIManagedDocument를 살펴 보지 못했지만 Xcode에서 "핵심 데이터 사용"을 선택하는 옵션이 여전히 있습니다. – jackslash

+0

그래, 관리되는 문서를 어디서나 가져올 수 없으며 코드도 제대로 작동하므로 잘 처리 할 것 같습니다. 그래서! 그 덕분입니다. 당신이 애플 리케이션 델리게이트에서 그것을 지킬 수 있다는 것을 깨닫지 못했고 네가 맞다면, 당신은 여전히 ​​핵심 데이터를 체크 할 수 있습니다, 나는 틀린 장소에서 찾고있었습니다. 도움을 청합니다. 나중에 참조 할 때이 코드를 응용 프로그램 대리인에 넣으려면 관리 대상 개체 컨텍스트/모델을 검색하는 방법은 무엇입니까? App 대리자가 루트 컨트롤러를 실행하고 그 시점에서 설정할 수있는 예제를 보았습니다.하지만 내보기 컨트롤러가 스토리 보드에서 빠져 나오고 있습니다 ... – Alan

관련 문제