使用核心数据的后台获取

时间:2013-12-07 17:34:25

标签: objective-c core-data

我正在阅读“iOS 7编程手册”,我似乎无法根据我的问题标题运行脚本。基本上,我试图在后台队列中创建一些记录,然后在主队列中获取结果,但在运行代码时没有任何内容传递给控制台。以下是示例中使用的方法。我在这里缺少什么?

- (void) populateDatabase{

    for (NSUInteger counter = 0; counter < 1000; counter++){
        Person *person =
        [NSEntityDescription
         insertNewObjectForEntityForName:NSStringFromClass([Person class])
         inManagedObjectContext:self.managedObjectContext];

        person.firstName = [NSString stringWithFormat:@"First name %lu",
                            (unsigned long)counter];

        person.lastName = [NSString stringWithFormat:@"Last name %lu",
                           (unsigned long)counter];
        person.age = @(counter);
    }

    NSError *error = nil;
    if ([self.managedObjectContext save:&error]){
        NSLog(@"Managed to populate the database.");
    } else {
        NSLog(@"Failed to populate the database. Error = %@", error);
    }

}

- (void) processPersons:(NSArray *)paramPersons{
    for (Person *person in paramPersons){
        NSLog(@"First name = %@, last name = %@, age = %ld",
              person.firstName,
              person.lastName,
              (long)person.age.integerValue);
    }
}

- (NSFetchRequest *) newFetchRequest{

    NSFetchRequest *request = [[NSFetchRequest alloc]
                               initWithEntityName:
                               NSStringFromClass([Person class])];

    request.fetchBatchSize = 20;
    request.predicate =
    [NSPredicate predicateWithFormat:@"(age >= 100) AND (age <= 200)"];

    request.resultType = NSManagedObjectIDResultType;
    return request;

}

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

    __weak NSManagedObjectContext *mainContext = self.managedObjectContext;
    __weak AppDelegate *weakSelf = self;
    __block NSMutableArray *mutablePersons = nil;

    /* Set up the background context */
    NSManagedObjectContext *backgroundContext =
    [[NSManagedObjectContext alloc]
     initWithConcurrencyType:NSPrivateQueueConcurrencyType];

    backgroundContext.persistentStoreCoordinator =
    self.persistentStoreCoordinator;

    /* Issue a block on the background context */
    [backgroundContext performBlock:^{

        NSError *error = nil;
        NSArray *personIds = [backgroundContext
                              executeFetchRequest:[weakSelf newFetchRequest]
                              error:&error];

        if (personIds != nil && error == nil){
            mutablePersons = [[NSMutableArray alloc]
                              initWithCapacity:personIds.count];

            /* Now go on the main context and get the objects on that 
             context using their IDs */
            dispatch_async(dispatch_get_main_queue(), ^{
                for (NSManagedObjectID *personId in personIds){
                    Person *person = (Person *)[mainContext
                                                objectWithID:personId];
                    [mutablePersons addObject:person];
                }
                [weakSelf processPersons:mutablePersons];
            });
        } else {
            NSLog(@"Failed to execute the fetch request.");
        }
    }];

    self.window = [[UIWindow alloc]
                   initWithFrame:[[UIScreen mainScreen] bounds]];

    self.window.backgroundColor = [UIColor whiteColor];
    ViewController *viewController = [[ViewController alloc] init];
    self.window.rootViewController = viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

0 个答案:

没有答案