2010-01-08 80 views

回答

5

在Xcode中創建新的iPhone應用程序項目時,大多數模板都允許「使用核心數據進行存儲」選項。勾選此選項,應用程序委託將包括一些樣板核心數據的代碼,包括該塊打開和/或創建持久性存儲:

/** 
Returns the persistent store coordinator for the application. 
If the coordinator doesn't already exist, it is created and the application's store added to it. 
*/ 
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 

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

    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"App.sqlite"]]; 

    NSError *error = nil; 
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) { 
     /* 
     Replace this implementation with code to handle the error appropriately. 

     abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. 

     Typical reasons for an error here include: 
     * The persistent store is not accessible 
     * The schema for the persistent store is incompatible with current managed object model 
     Check the error message to determine what the actual problem was. 
     */ 
     //NSLog(@"Error with persistent store %@, %@", error, [error userInfo]); 
     NSLog(@"Error with persistent store (did the data model change?)"); 
     abort(); 
    } 

    return persistentStoreCoordinator; 
} 
+0

你的意思是它會自動創建SQLite作爲持久性存儲。 請稍後回覆。 – uttam 2010-01-08 06:46:11

+1

是的,這段代碼可以。如果答案有幫助,請接受你的問題的答案。 – gerry3 2010-01-08 06:56:31

+0

如果我想在其中添加數據,那麼我可以如何添加? – uttam 2010-01-08 08:37:53

相關問題