2014-02-18 81 views
0

雖然繼電子書http://timroadley.com/我插入。但是當我在sqlite中檢查他們沒有數據存在它。我也用-com.apple.CoreData.SQLDebug進行調試,但沒有查詢顯示。 Source Code核心數據:數據沒有被保存起來

解決方案: - 數據將只在sqlite的表現時,我會終止應用程序或按home鍵後,程序將會在後臺。

AppDelegate.h

#import <UIKit/UIKit.h> 
    #import "CoreDataHelper.h" 
    #import <CoreData/CoreData.h> 
    @interface AppDelegate : UIResponder <UIApplicationDelegate> 
    @property (strong, nonatomic) UIWindow *window; 
    @property (nonatomic, strong, readonly) CoreDataHelper *coreDataHelper; 
    @end 

AppDelegate.m

- (void)demo { 

    NSArray *newItemNames = [NSArray arrayWithObjects: 
          @"Apples", @"Milk", @"Bread", @"Cheese", @"Sausages", @"Butter", @"Orange Juice", @"Cereal", @"Coffee", @"Eggs", @"Tomatoes", @"Fish", nil]; 
    for (NSString *newItemName in newItemNames) { 
     Item *newItem = 
     [NSEntityDescription insertNewObjectForEntityForName:@"Item" inManagedObjectContext:_coreDataHelper.context]; 
     newItem.name = newItemName; 
     NSLog(@"Inserted New Managed Object for '%@'", newItem.name); 
    } 
} 

- (CoreDataHelper*)cdh { 
    if (!_coreDataHelper) { 
     _coreDataHelper = [CoreDataHelper new]; 
     [_coreDataHelper setupCoreData]; 
    } 
    return _coreDataHelper; 
} 
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    return YES; 
} 
- (void)applicationDidEnterBackground:(UIApplication *)application 
{ 
    [[self cdh] saveContext]; 
} 
- (void)applicationDidBecomeActive:(UIApplication *)application 
{ 
    [self cdh]; 
    [self demo]; 
} 

- (void)applicationWillTerminate:(UIApplication *)application 
{ 
    [[self cdh] saveContext]; 
} 

CoreDataHelper.h

@property(nonatomic,readonly) NSManagedObjectContext *context; 
@property(nonatomic,readonly) NSManagedObjectModel *model; 
@property(nonatomic,readonly) NSPersistentStore *store; 
@property(nonatomic,readonly) NSPersistentStoreCoordinator *coordinator; 

-(void)setupCoreData; 
-(void)saveContext; 

CoreDataHelper.m

#pragma mark - FILES 
    NSString *storeFilename = @"Grocery-Dude.sqlite"; 

    #pragma mark - PATHS 
    - (NSString *)applicationDocumentsDirectory { 
     return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) lastObject]; 
    } 
    - (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]) { 
         } 
      else { 
       NSLog(@"FAILED to create Stores directory: %@", error);} 
     } 
     return storesDirectory; 
    } 
    - (NSURL *)storeURL { 
     return [[self applicationStoresDirectory] 
       URLByAppendingPathComponent:storeFilename]; 
    } 

    #pragma mark - SETUP 
    - (id)init { 
     self = [super init]; 
     if (!self) {return nil;} 
     _model = [NSManagedObjectModel mergedModelFromBundles:nil]; 
     _coordinator = [[NSPersistentStoreCoordinator alloc] 
         initWithManagedObjectModel:_model]; 
     _context = [[NSManagedObjectContext alloc] 
        initWithConcurrencyType:NSMainQueueConcurrencyType]; 
     [_context setPersistentStoreCoordinator:_coordinator]; 
     return self; 
    } 
    - (void)loadStore { 
     if (_store) {return;} // Don’t load store if it's already loaded 
     NSDictionary *options = 
     @{NSSQLitePragmasOption: @{@"journal_mode": @"DELETE"}}; 

     NSError *error = nil; 
     _store = [_coordinator addPersistentStoreWithType:NSSQLiteStoreType 
              configuration:nil 
                 URL:[self storeURL] 
                options:options error:&error]; 
     if (!_store) {NSLog(@"Failed to add store. Error: %@", error);abort();} 
     else   {NSLog(@"Successfully added store: %@", _store);} 
    } 
    - (void)setupCoreData { 
     [self loadStore]; 
    } 

    #pragma mark - SAVING 
    - (void)saveContext { 

     if ([_context hasChanges]) { 
      NSError *error = nil; 
      if ([_context save:&error]) { 
       NSLog(@"_context SAVED changes to persistent store"); 
      } else { 
       NSLog(@"Failed to save _context: %@", error); 
      } 
     } else { 
      NSLog(@"SKIPPED _context save, there are no changes!"); 
     } 
    } 
+0

,你錯過了34頁,它說的底部是否有機會'需要被禁用,因此您可以將此日誌模式檢查Grocery-Dude的內容。' – Desdenova

+0

@ Desdenova-我嘗試了零而不是選項,但它仍然沒有在sqlite中顯示數據,但是,Akhilrajtr的答案正在工作。 – iOS

+2

也許我錯了,但我跑了你的應用程序。然後將該應用程序發送到後臺。然後檢查生成的sqlite文件。一切都正確存儲。 http://cl.ly/image/2S1a3z3i3K3K。 你保存的一切似乎都在那裏。 – DennyLou

回答

1

嘗試在循環本身節省item

NSArray *newItemNames = [NSArray arrayWithObjects: 
         @"Apples", @"Milk", @"Bread", @"Cheese", @"Sausages", @"Butter", @"Orange Juice", @"Cereal", @"Coffee", @"Eggs", @"Tomatoes", @"Fish", nil]; 
for (NSString *newItemName in newItemNames) { 
    Item *newItem = 
    [NSEntityDescription insertNewObjectForEntityForName:@"Item" inManagedObjectContext:_coreDataHelper.context]; 
    newItem.name = newItemName; 
    NSLog(@"Inserted New Managed Object for '%@'", newItem.name); 
    [[self cdh] saveContext]; 
} 
+0

@ Akhilrajtr-謝謝,這是工作,但在接受你的答案之前,我想知道別人的觀點。因爲在每個循環中保存並不是一個好習慣 – iOS