可悲的是我只知道对这个问题的丑陋的解决方案。
在你User
.m文件实现setProfilePicture:
这样的:
//NOT TESTED IN A MULTITHREADED ENV
- (void) setProfilePicture:(NSData *)data
{
[self willChangeValueForKey:@"profilePicture"];
[self setPrimitiveValue:data forKey:@"profilePicture"];
[self.posts enumerateObjectsUsingBlock:^(Post* p, BOOL *stop) {
[p willChangeValueForKey:@"user"];
[p didChangeValueForKey:@"user"];
}];
[self didChangeValueForKey:@"profilePicture"];
}
这将通知FRC,邮政元素都有变化。
您可能会发现更多的信息here
编辑:
要提取的访问,你可以添加到您的User
.M数据:
//UNTESTED
+ (void) mergeToMain:(NSNotification*)notification
{
AppDelegate* appDel = (AppDelegate*)[[UIApplication sharedApplication] delegate];
[appDel.managedObjectContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:)
withObject:notification
waitUntilDone:YES];
}
- (NSData*)_profilePicture
{
return [self primitiveValueForKey:@"profilePicture"];
}
- (NSData*) profilePicture
{
[self willAccessValueForKey:@"profilePicture"];
NSData* picData = [self primitiveValueForKey:@"profilePicture"];
if (!name) {
__block NSManagedObjectID* objectID = self.objectID;
//This solves the multiple downloads per item by using a single queue
//for all profile pictures download.
//There are more concurrent ways to accomplish that
dispatch_async(downloadSerialQueue, ^{ //define some serial queue for assuring you down download multiple times the same object
NSError* error = nil;
AppDelegate* appDel = (AppDelegate*)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext* context = [[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:appDel.persistentStoreCoordinator];
[context setUndoManager:nil];
User* user = (User*)[context existingObjectWithID:objectID error:&error];
if (user && [user _profilePicture] == nil) {
NSData *data = //[method to retrieve data from server];
if (data) {
if (user) {
user.profilePicture = data;
} else {
NSLog(@"ERROR:: error fetching user: %@",error);
return;
}
[[NSNotificationCenter defaultCenter] addObserver:[self class] selector:@selector(mergeToMain:) name:NSManagedObjectContextDidSaveNotification object:context];
[context save:&error];
[[NSNotificationCenter defaultCenter] removeObserver:[self class] name:NSManagedObjectContextDidSaveNotification object:context];
}
}
});
}
[self didAccessValueForKey:@"profilePicture"];
return picData;
}
嗯,我将不得不尝试这个,它似乎并不丑陋......在多线程环境下,那些KVO消息需要在m ain线程? – inks2002 2013-04-26 19:06:50
我相信它可以工作,但还没有测试过(稍后会这样做) – 2013-04-26 19:08:53
已测试,并且在合并其他线程的更改时进行更新。 – 2013-04-26 19:18:50