0

iOS 8.1 で CoreData に問題があります。私のデバイスでは、すべてのシミュレーターでコードが正常に実行されている間、常にこのエラーが発生します。

Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" UserInfo=0x15e62bd0 {reason=Failed to create file; code = 1} with userInfo dictionary {
reason = "Failed to create file; code = 1";
}

すでにデバイスからアプリを削除しようとしました。テキストファイルを手動で作成しようとしましたが成功しました。エラーの原因となるコード スニペットは次のとおりです。

- (NSPersistentStoreCoordinator*) persistentStoreCoordinator {
  NSError* error = nil;
  NSURL* storeURL = [[[NSBundle mainBundle] resourceURL] URLByAppendingPathComponent: @"users.sqlite"];

  if (_persistentStoreCoordinator != nil)
    return _persistentStoreCoordinator;

  _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
  if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
    error = nil;
    [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil];
    [_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
  }

  return _persistentStoreCoordinator;
}

編集:

jrturton さん、ご回答ありがとうございます。解決策は

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSURL* storeURL = [NSURL fileURLWithPath:[documentsDirectory stringByAppendingString:@"/users.sqlite"] isDirectory:NO];
4

1 に答える 1

3

アプリのバンドルはデバイスでは読み取り専用ですが、シミュレーターでは読み取り専用ではありません。

作成storeURL中は、アプリのバンドルを指す URL を作成しています。代わりにドキュメント ディレクトリを使用する必要があります。

于 2014-10-25T22:22:39.970 に答える