簡體   English   中英

無法將sqlite文件從應用程序捆綁包復制到文檔目錄:正在獲取(可可錯誤260)

[英]Unable to copy sqlite file from app bundle to documents directory: getting (Cocoa error 260)

我正在嘗試使用以下代碼將我的sqlite文件從應用程序捆綁包復制到文檔目錄中

-(id)init {

    self = [super init];
    if (self) {

// 1.為UIManagedDocument創建數據庫文件的句柄

        NSURL *docURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
        docURL = [docURL URLByAppendingPathComponent:@"DefaultDatabase"];
        self.document =  [[UIManagedDocument alloc] initWithFileURL:docURL]; // URL of the location of document i.e. /documents directory
    NSLog(@" URL document");

        //set our document up for automatic migrations

        if (self.document) {
            NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithBool:YES],
            NSMigratePersistentStoresAutomaticallyOption,
                                 [NSNumber numberWithBool:YES],
            NSInferMappingModelAutomaticallyOption, nil];

            self.document.persistentStoreOptions = options;

            // Register for Notifications

            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(objectsDidChange:) name:NSManagedObjectContextObjectsDidChangeNotification object:self.document.managedObjectContext];

            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextDidSave:) name:NSManagedObjectContextDidSaveNotification object:self.document.managedObjectContext];
        } else {         
            NSLog(@"The UIManaged Document could not be initialized");

        }

// 2.在第一次運行的情況下檢查持久性存儲文件是否不存在

    if (!([[NSFileManager defaultManager] fileExistsAtPath:[self.document.fileURL path]])) {
        NSLog(@" persistent file not found trying to copy from app bbundle");
        NSString *docFileName = [UIManagedDocument persistentStoreName];
        NSString *docFilePath = [[NSBundle mainBundle] pathForResource:docFileName ofType:@"sqlite"];
        **NSLog(@" doc file path = %@", docFilePath);**
        if (docFilePath) { // found the database file in app bundle
            NSLog(@" found file in bundle");
            //Production: Copy from app bundle.
            NSError *error = nil;
            NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *copyToPath  = [searchPaths lastObject];
            if([[NSFileManager defaultManager] copyItemAtPath:docFilePath toPath:copyToPath error:&error]){
                NSLog(@"File successfully copied");
            } else { // if could not locate the file
                [[[UIAlertView alloc]initWithTitle:NSLocalizedString(@"error", nil) message: NSLocalizedString(@"failedcopydb", nil)  delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil)  otherButtonTitles:nil] show];
                NSLog(@"Error description-%@ \n", [error localizedDescription]);
                NSLog(@"Error reason-%@", [error localizedFailureReason]);
            }
        }
    }
}
return self;

}

a)我使用數據加載器應用程序創建了.sqlite文件,該應用程序使用UIManagedDcoument將數據添加到核心數據。 .sqlite文件在documents目錄中生成。

b)我將* .sqlite文件添加到資源文件夾,並將其添加到包中。 如果我使用終端機檢查應用程序捆綁包, <app name.momd>在捆綁包目錄下看到“持久存儲”和<app name.momd>文件。 沒有擴展名為.sqlite的文件

c)但是在上面的代碼中,當我使用代碼行檢查應用程序捆綁包中是否存在文件時,它是成功的。 所以文件存在於包中

   NSString *file = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];

d)但是,當嘗試復制時,它失敗並顯示我錯誤信息(Cocca錯誤206),這意味着它無法在應用程序包中找到.sqlite文件。

  if([[NSFileManager defaultManager] copyItemAtPath:file toPath:copyToPath error:&error])

這符合以下事實:我在應用程序捆綁包目錄下沒有看到.sqlite文件,而是看到了持久存儲和.momd文件。

那么我要去哪里錯了?

編輯

這是有關如何生成mydata.sqlite文件的說明。

我正在使用Core Data,並希望在首次向用戶啟動應用程序時提供一個預先填充的數據庫。 因此,我使用數據加載器應用程序為我創建了.sqlite文件。 我正在使用UIManagedDocument作為核心數據。 運行該應用程序后,我看到在documents目錄下創建了一個mydata.sqlite目錄。 目錄結構如下

/users//.../documents/mydata.sqlite/storeContent/persistenStore。

因此,基本上,它不是創建文件,而是創建帶有.sqlite擴展名的目錄,並且我看到了persistentStore文件。 因此,當我嘗試在構建階段在目標中的應用程序包下復制資源時,它會添加persistentStore而不是.sqlite文件。

我的問題無論描述如何都是正確的,應該在我的代碼中以不同的方式處理。 如果是,我應該怎么做才能處理數據存儲。

我以為.sqlite是文件而不是目錄。 請指導

謝謝

該行實際上並不檢查文件是否存在:

NSString *file = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];

所有要做的就是在file構建路徑。 如果要檢查是否存在,則需要使用[NSFileManager fileExistsAtPath:] 或者,您可以返回使用pathForResource:ofType:當它返回nil時,這顯然是正確的。

您似乎根本沒有將文件復制到捆綁軟件中。 這是您的Xcode項目配置存在的問題。

我在UIManagedDocument上閱讀了蘋果文檔 ,這是我犯錯的關鍵點

  1. 錯誤地處理了UIManagedDocument。 初始化托管文檔時,請指定文檔位置的URL 而不是文檔本身。 如果需要添加

  2. 您可以通過創建UIManagedDocument的子類(即OverridepersistentStoreName)來執行其他自定義,以自定義文檔文件包中的持久性存儲文件的名稱。

  3. 剪切和粘貼示例代碼以正確的方式處理數據文件

您可以使用initWithFileURL:創建一個托管文檔對象: 如果需要,可以在使用文檔的受管對象上下文之前對其進行配置。 通常,您可以設置持久性存儲選項,如本示例所示:

NSURL *docURL = [[self applicationDocumentsDirectory]        URLByAppendingPathComponent:@"FirstDocument"];
 doc = [[UIManagedDocument alloc] initWithFileURL:docURL];

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
 [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
 [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
doc.persistentStoreOptions = options;


**if ([[NSFileManager defaultManager] fileExistsAtPath:[docURL path]]**) {
   [doc openWithCompletionHandler:^(BOOL success){
    if (!success) {
        // Handle the error.
    }
    }];
 }
  else {
   [self addInitialData];
   [doc saveToURL:docURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){
      if (!success) {
        // Handle the error.
     }
     }];
    } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM