核心数据:数据尚未保存

时间:2014-02-18 11:28:09

标签: ios iphone core-data

跟随我插入的http://timroadley.com/电子书。但是当我检查sqlite时,它们中没有数据。我也使用-com.apple.CoreData.SQLDebug进行调试,但没有显示任何查询。Source Code

解决方案: - 数据只会在我终止应用时显示在sqlite中,否则应用会在按下主页按钮后进入后台。

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!");
        }
    }

1 个答案:

答案 0 :(得分: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];
}
相关问题