【问题标题】:removeitematpath to remove Olddb.sqliteremoveitematpath 删除 Olddb.sqlite
【发布时间】:2011-04-05 20:24:22
【问题描述】:

我得到了这个需要用新数据库更新的应用程序。

我想删除旧的并用新的替换它。

这是我正在使用的代码:

 - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

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


     NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"Newdb.sqlite"];

     NSFileManager *fileManager = [NSFileManager defaultManager];
     // If the expected store doesn't exist, copy the default store.
     if (![fileManager fileExistsAtPath:storePath]) {
          NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Newdb" ofType:@"sqlite"];
          if (defaultStorePath) {
               [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
          }
     }

     NSURL *storeUrl = [NSURL fileURLWithPath:storePath];

     NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber   numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; 
     persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];

     NSError *error;
     if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {

          NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
          exit(-1);  // Fail
     }    

     return persistentStoreCoordinator;
}

我希望我的应用在启动时检查 Olddb.sqlite 是否存在,如果存在则删除它!

【问题讨论】:

    标签: iphone file nsfilemanager delete-file


    【解决方案1】:

    这是解决方案...

    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docsDir = [documentPaths objectAtIndex:0];
        NSString *pathInDocuments = [docsDir stringByAppendingPathComponent:@"Olddb.sqlite"];
    if (pathInDocuments) {
        [fileManager removeItemAtPath:pathInDocuments error:NULL];
    }
    

    【讨论】:

    • 这是不正确的。这将检查 NSString pathInDocuments 是否不是 nil 并根据它删除文件,而不是使用 [fileManager fileExistsAtPath:pathInDocuments] 检查实际文件是否存在
    猜你喜欢
    • 2013-01-06
    • 1970-01-01
    • 2012-12-05
    • 2018-10-25
    • 2011-06-05
    • 2012-01-23
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多