这是一个需要处理的大问题,但通常您会在 appdelegate.m 的 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 中添加类似这样的内容(如果您使用的是 UIManagedDocument):
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] firstObject];
NSString *documentName = @"YOUR_DATABASE_NAME";
NSURL *url = [documentsDirectory URLByAppendingPathComponent:documentName];
self.document = [[UIManagedDocument alloc] initWithFileURL:url];
BOOL fileExists = [fileManager fileExistsAtPath:[url path]];
if (fileExists) {
[self.document openWithCompletionHandler:^(BOOL success) {
if (success) {
self.context = self.document.managedObjectContext;
// Post notification so others can gather the document and context
[[NSNotificationCenter defaultCenter] postNotificationName:@"DatabaseReady"
object:self];
}
if (!success) NSLog(@"couldn't open file at %@", url);
}];
} else {
[self.document saveToURL:url
forSaveOperation:UIDocumentSaveForCreating
completionHandler:^(BOOL success) {
if (success) {
self.context = self.document.managedObjectContext;
// Post notification so others can gather the document and context
[[NSNotificationCenter defaultCenter] postNotificationName:@"DatabaseReady"
object:self];
}
if (!success) NSLog(@"couldn't open file at %@", url);
}];
}
您应该将@property (strong, nonatomic) UIManagedDocument *document; 放入您的appdelegate 的.h 文件中,以便其他视图控制器可以获取该文档。在需要以某种方式联系数据库的视图控制器中,添加以下内容:
- (void)awakeFromNib
{
// Listen for UIManagedDocument so that we can get the database set up right
// This only works in awakeFromNib (viewDidLoad is too late)
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(getUIManagedDocument:)
name:@"DatabaseReady"
object:nil];
}
然后,您需要将getUIManagedDocument: 方法添加到您的视图控制器:
- (void)getUIManagedDocument:(NSNotification *)notification
{
self.document = [(OneWorldAppDelegate *)[[UIApplication sharedApplication] delegate] document];
self.context = self.document.managedObjectContext;
}
当然你需要添加
@property (strong, nonatomic) UIManagedDocument *document;
@property (strong, nonatomic) NSManagedObjectContext *context;
到您的文件。这就是self.context 的来源。
此时,您已准备好开始使用数据库。
重要提示:不要忘记在视图控制器中#import您的 appdelegate 的 .h 文件,您要在其中访问 appdelegate 的 @property document!
就获取 JSON 数据而言,我建议您阅读教程,例如 this one。它解释得很清楚。
希望对你有帮助!