CoreData的基本使用

概述:把对象存储进CoreData,大概是这个情况:
CoreData的基本使用_第1张图片
CoreData的基本使用_第2张图片
那么问题来了:
1.哪设置存储文件路径(full path)?
2.

1.关于UIManagedDocument
1.1Creating a UIManagedDocument
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] firstObject];
NSString *documentName = @“MyDocument”;
NSURL *url = [documentsDirectory URLByAppendingPathComponent:documentName];
UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:url];
注意:This creates the UIManagedDocument instance, but does not open nor create the underlying file(只创建了UIManagedDocument,并还没有打开或者创建了底层的文件)。

1.2How to open or create a UIManagedDocument
1)First, check to see if the UIManagedDocument’s underlying file exists on disk …
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[url path]] ;
… if it does, open the document using …
[document openWithCompletionHandler:^(BOOL success) { /* block to execute when open */ }];
… if it does not, create the document using …
[document saveToURL:url // could (should?) use document. fileURL property here
forSaveOperation:UIDocumentSaveForCreating
competionHandler:^(BOOL success) { /* block to execute when create is done */ }];
解释:用NSFileManager 去检测是否已创建了对应URL([URL path])的文件,是就打开该文件(openWithCompletionHandler:),否则创建该文件(saveToURL:forSaveOperation:completionHandler:)。具体看苹果官方文档:https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDocument_Class/index.html#//apple_ref/occ/cl/UIDocument
2) Example
self.document = [[UIManagedDocument alloc] initWithFileURL: (URL *)url];
if ([[NSFileManager defaultManager] fileExistsAtPath: [url path]]) {
[document openWithCompletionHandler: ^(BOOL success) {
if (success) [self documentIsReady];
if (!success) NSLog(@“couldn’t open document at %@”, url);
}];
} else {
[document saveToURL: url forSaveOperation: UIDocumentSaveForCreating
completionHandler: ^(BOOL success) {
if (success) [self documentIsReady];
if (!success) NSLog(@“couldn’t create document at %@”, url);
}];
}
// can’t do anything with the document yet (do it in documentIsReady)
检查文件状态
Once document is open/created, you can start using it
But you might want to check the documentState when you do …
- (void) documentIsReady
{
if (self.document. documentState == UIDocumentStateNormal) {
// start using document
}
}

你可能感兴趣的:(IOS)