Core Data相關之配置數(shù)據(jù)存儲
本代碼是在應用沙盒目錄下創(chuàng)建一個Stores文件夾膛锭,然后在文件夾中創(chuàng)建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{
return NSHomeDirectory();
}
2.在程序文檔目錄中添加名為Stores的子目錄,并將其路徑放在URL中返回,若Stores目錄尚未建立饲漾,則建立。
api詳解:
//判斷路徑是否有效
- (BOOL)fileExistsAtPath:(NSString *)path;
//根據(jù)url創(chuàng)建目錄
//createIntermediates為YES可以創(chuàng)建多級目錄,NO創(chuàng)建一級目錄
//attributes字典類型缕溉,配置這個文件信息如創(chuàng)建時間考传,讀寫等
//error如果創(chuàng)建失敗,可以通過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.配置數(shù)據(jù)存儲
//storeTypeg共四種類型SQLite证鸥,XML僚楞,Binary,InMemory
//storeURL及數(shù)據(jù)存儲在文檔中的URL地址
//- (NSPersistentStore *)addPersistentStoreWithType:(NSString *)storeType
configuration:(NSString *)configuration
URL:(NSURL *)storeURL
options:(NSDictionary *)options
error:(NSError **)error;
數(shù)據(jù)存儲的聲明
@property (nonatomic, readonly) NSPersistentStore *store;
_store = [_coordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:[self storeURL]
options:nil error:&error];
參考資料:
「Learning Core Data for iOS」示例代碼