CoreData Fetched& return空数组:o

时间:2016-01-29 18:53:47

标签: ios core-data

我试图一次又一次地重写代码。 但仍然有空的数据。

试着关注一些核心DataBook。

制作基本模型/实体/, 制作一个基本的1000a项然后保存到上下文。

但是当尝试获取时,总是返回一个Empty数组。 故障也设置= NO;

我想知道我的代码是否有问题。 我以为我已经按照书中的所有内容。但还是......

//  AppDelegate.m
//  DudeRaw
//
//  Created by Zenjougahara on 11/20/15.
//  Copyright © 2015 Zenjougahara. All rights reserved.
//

#import "AppDelegate.h"
#import "CoreDataHelper.h"

@interface AppDelegate ()

@property (strong,nonatomic) CoreDataHelper* CD;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

   // [self.CD makePSConce];   /// create PSC on HDD only once
   // [self.CD insertDataToContext];
      [self.CD fetchdata];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    /// SaveContext here !!
    [self.CD saveContext];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    /// SaveContext here !!
    [self.CD saveContext];
}

-(CoreDataHelper*) CD{
    if(!_CD){
        _CD =  [[CoreDataHelper alloc]init];
        [_CD setupCoreData];
    }
    return _CD;
}


@end
//
//  CoreDataHelper.m
//  DudeRaw
//
//  Created by Zenjougahara on 11/20/15.
//  Copyright © 2015 Zenjougahara. All rights reserved.
//

#import "CoreDataHelper.h"
#import "Item.h"

@interface CoreDataHelper ()

@property (strong,nonatomic,readwrite) NSManagedObjectContext* con;
@property (strong,nonatomic,readwrite) NSManagedObjectModel* mo;
@property (strong,nonatomic,readwrite) NSPersistentStoreCoordinator* psc;
@property (strong,nonatomic,readwrite) NSPersistentStore* pstore;

@end

@implementation CoreDataHelper

#pragma mark FilePaths

-(NSURL*) originalDocumentURL{

    NSFileManager* fm = [NSFileManager defaultManager];
    return [[fm  URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject];
}

-(NSString*) folderName {
    return @"ProjectDxD";
}

-(NSString*) fileName{
    return @"MYCORED.sqlite";
}

-(NSURL*) withfolderURL {
    return [[self originalDocumentURL] URLByAppendingPathComponent:[self folderName]];
}

-(NSURL*) finalFileNameURL {
    NSURL* a  = [self withfolderURL];
    return [a URLByAppendingPathComponent: [self fileName]];
} // use this one

#pragma  mark PUBLIC METHODS

-(void)saveContext {
    NSError* err;
    if([_con hasChanges]){
        [_con save:&err];
    }
}
-(void) setupCoreData{
    _mo  =  [NSManagedObjectModel mergedModelFromBundles:nil];
    _psc =  [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:_mo];
    _con =  [[NSManagedObjectContext alloc]initWithConcurrencyType:NSMainQueueConcurrencyType];
    _con.persistentStoreCoordinator = _psc;

}  // setUP "not using LAZY init (cuz this is not thread- safe)


#pragma mark Method UsingOnce


-(void) makePSConce {
    NSError* err;
    NSFileManager* mng = [NSFileManager defaultManager];
    if([mng fileExistsAtPath: [self finalFileNameURL].path]){
        return ;
    } else {
        [mng createDirectoryAtPath: [self withfolderURL].path
                    withIntermediateDirectories:YES
                    attributes:nil error:&err];
    }
    NSDictionary* op =  @{NSSQLitePragmasOption : @{@"journal_mode":@"DELETE"},
                          NSInferMappingModelAutomaticallyOption :@YES,
                          NSMigratePersistentStoresAutomaticallyOption:@YES};

    _pstore = [_psc addPersistentStoreWithType:NSSQLiteStoreType
                             configuration:nil URL:[self finalFileNameURL]
                                   options:op error:&err];

}

-(void) insertDataToContext{
    NSError* err;
    for(int i = 1;i<=1000;i++){
        Item* a = [NSEntityDescription insertNewObjectForEntityForName:@"Item"
                                      inManagedObjectContext:_con];
        a.name =  [NSString stringWithFormat:@"nameis + [%i]" , i];
        NSLog(@"name is %@",a.name);

        [_con save:&err];
    }
}

-(void) fetchdata{
    NSFetchRequest * req = [NSFetchRequest fetchRequestWithEntityName:@"Item"];
    [req setReturnsObjectsAsFaults:NO];

    NSEntityDescription* des = [NSEntityDescription entityForName:@"Item"
                                           inManagedObjectContext:_con];
    [req setEntity:des];
    NSSortDescriptor* sort = [NSSortDescriptor sortDescriptorWithKey:@"name"
                                                           ascending:YES];
    [req setSortDescriptors: [NSArray arrayWithObjects:sort, nil]];
    NSError* err;
    NSArray* a = [_con executeFetchRequest:req error:&err];

    NSLog(@"show me what fetched %@",a);

}

@end

这是日志告诉我的事情

第一次运行)一切正常,插入,取出和登录

Homebutton - &gt;关闭申请

1stRun

2nd RUN)仅获取,空数组:( 2ndRUN

1 个答案:

答案 0 :(得分:0)

检查fetch是否返回错误。如果有,这将帮助您了解出了什么问题。如果没有错误且数组== nil,则没有与请求匹配的对象,您可以从那里查看代码。

此外,在调试CoreData时,这是我最喜欢的工具之一:

-com.apple.CoreData.SQLDebug 1可以作为参数传入,这将准确记录您的提取所需的时间以及返回的对象数。还可以让您更好地了解我的问题在哪里发生。

这些可以帮助您准确找出代码出错的位置。