Core|Core Data相关之配置数据存储

Core Data相关之配置数据存储
本代码是在应用沙盒目录下创建一个Stores文件夹,然后在文件夹中创建Grocery-Dude.sqlite文件。
1.获取应用程序文档路径(两种方法,注意两种方法返回路径不同)

//这是应用程序文档目录的路径 /Users/apple/Library/Application Support/iPhone Simulator/4.3/Applications/550AF123-1711-3124-881B-54329FAA32B7/Documents- (NSString *)applicationDocumentsDirectory { return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) lastObject]; }//这是应用程序目录的路径 /Users/apple/Library/Application Support/iPhone Simulator/4.3/Applications/550AF26D-174B-42E6-881B-B7499FAA32B7/- (NSString *)applicationDirectory{ returnNSHomeDirectory(); }

2.在程序文档目录中添加名为Stores的子目录,并将其路径放在URL中返回,若Stores目录尚未建立,则建立。
api详解://判断路径是否有效 - (BOOL)fileExistsAtPath:(NSString *)path; //根据url创建目录 //createIntermediates为YES可以创建多级目录,NO创建一级目录 //attributes字典类型,配置这个文件信息如创建时间,读写等 //error如果创建失败,可以通过error打印失败原因 - (BOOL)createDirectoryAtURL:(NSURL *)url withIntermediateDirectories:(BOOL)createIntermediates attributes:(NSDictionary *)attributes error:(NSError **)error- (NSURL *)applicationStoresDirectory { NSURL *storesDirectory = [[NSURL fileURLWithPath:[self applicationDocumentsDirectory]]URLByAppendingPathComponent:@"Stores"]; NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:[storesDirectory path]]) { NSError *error = nil; if ([fileManager createDirectoryAtURL:storesDirectory withIntermediateDirectories:YES attributes:nil error:&error]) { if (debug==1) { NSLog(@"Successfully created Stores directory"); } } else {NSLog(@"FAILED to create Stores directory: %@", error); } } return storesDirectory; }

3.将Grocery-Dude.sqlite添加到URL路径中并返回
- (NSURL *)storeURL {return [[self applicationStoresDirectory]URLByAppendingPathComponent:storeFilename]; //返回的是一个具体到Grocery-Dude.sqlite的URL }

4.配置数据存储
//storeTypeg共四种类型SQLite,XML,Binary,InMemory //storeURL及数据存储在文档中的URL地址 //- (NSPersistentStore *)addPersistentStoreWithType:(NSString *)storeType configuration:(NSString *)configuration URL:(NSURL *)storeURL options:(NSDictionary *)options error:(NSError **)error; 数据存储的声明 @property (nonatomic, readonly) NSPersistentStore *store; _store = [_coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[self storeURL] options:nil error:&error];

【Core|Core Data相关之配置数据存储】参考资料:
「Learning Core Data for iOS」示例代码

    推荐阅读