1

那时我正在失去头发,所以我想我会接触到这里有过使用带有线程和核心数据的 Objective C 经验的优秀人才。我在从主线程访问的 NSPrivateQueue 上下文中的线程上插入托管对象时遇到问题。因此,在较高级别上,我使用 AFNetworking 生成一个线程来发出请求以从服务器检索 JSON 数据,然后将值插入到我的持久存储核心数据中。完成此操作后,我还有另一个线程用于使用 AFNetworking 下载一些二进制数据。我为此设置了 2 个托管上下文,如下所示:

(NSManagedObjectContext *)masterManagedContext {
if (_masterManagedContext != nil) {
    return _masterManagedContext;
}

NSPersistentStoreCoordinator *coord = [self coordinator];
if (coord != nil) {
    _masterManagedContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
     _masterManagedContext.stalenessInterval = 0.0;
    [_masterManagedContext performBlockAndWait:^{
        [_masterManagedContext setPersistentStoreCoordinator:coord];
    }];

}
return _masterManagedContext;
}


// Return the NSManagedObjectContext to be used in the background during sync
- (NSManagedObjectContext *)backgroundManagedContext {
if (_backgroundManagedContext != nil) {
 return _backgroundManagedContext;
 }

NSManagedObjectContext *masterContext = [self masterManagedContext];
if (masterContext != nil) {
    _backgroundManagedContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
     _backgroundManagedContext.stalenessInterval = 0.0;
    [_backgroundManagedContext performBlockAndWait:^{
        [_backgroundManagedContext setParentContext:masterContext];
    }];
}

return _backgroundManagedContext;

}

如上所示,我正在使用子上下文和父上下文。当我打电话来获取 json 数据时,我有如下内容:

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        //Initially delete all records in table. This will change
         [[Singleton sharedInstance]removeEntityObjects:className];

           for (int x=0; x < [JSON count]; x++) {
                NSMutableDictionary *curDict = [JSON objectAtIndex:x];
                   [[CoreDatam sharedinstance] insertEmployeesWithDictionary:curDict];

                }else  {
                    /* do nothing */
                }
            }
        }

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error,id JSON) {

        [delegate performSelector:@selector(didNotCompleteSync:) withObject:className];
    }];

    [operations addObject:operation];
}    

[self.AFClient enqueueBatchOfHTTPRequestOperations:operations progressBlock:^(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations) {
    NSLog(@"Currenlty downloaded table data %d of %d!",numberOfCompletedOperations,totalNumberOfOperations);

} completionBlock:^(NSArray *operations) {

    if (_syncInProgress) {
          [[CoreDatam sharedInstance]updateEmpForId];



           [self downloadAllFiles];
    }
}];

}`

对于插入功能,我有如下内容:

 insertEmployeesWithDictionary:curDict {

[[self backgroundManagedContext]performBlockAndWait:^{
Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee"
                                                     inManagedObjectContext:[self backgroundManagedContext]];

/* Issues saving null into core data based on type.*/
[emp setFirst:[dictCopy objectForKey:@"first"]];
[emp setLast:[dictCopy objectForKey:@"last"]];


    NSError *error = nil;
    BOOL saved;
    saved = [[self backgroundManagedContext] save:&error];
    if (!saved) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }

    [self saveMasterContext];

}];

}

问题如下,我试图在上面完成块中的方法中访问托管对象:

updateEmpId {
[self.backgroundManagedContext performBlockAndWait:^{
     NSError *error = nil;
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Employee"];
    [request setSortDescriptors:[NSArray arrayWithObject:
                                 [NSSortDescriptor sortDescriptorWithKey:@"last" ascending:YES]]];

    myEmps = [self.backgroundManagedContext executeFetchRequest:request error:nil];

 for (Employee *moEmp in myEmps) {
        [[self backgroundManagedContext]refreshObject:moEmp mergeChanges:YES];
        moEmp.photo = @'default.pic';
 }
                NSError *saveError = nil;
                if (![self.backgroundManagedContext save:&saveError]) {
                NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
                }

            [self saveMasterContext];

}

问题是,在查看在主线程中修改的托管对象时,我的行为非常不一致。使用父子上下文关系时是否仍然需要传递托管的objectIds?如果是这样,我该怎么做上面的例子?非常感谢任何帮助。

4

1 回答 1

1

您应该在主线程上下文中传递NSManagedObjectIDs或重新获取,是的。如果您传递对象 ID,则在保存新的 Employee 对象后从后台上下文中获取 ID,并existingObjectWithID:error:在父上下文中使用以在其中实例化它们。或者只是updateEmpIdmasterManagedContext.

于 2013-03-05T02:22:01.000 回答