我正在尝试使用以下代码将实体插入或更新(如果存在)到核心数据中:
- (void)insertFriendWithDictionary:(NSDictionary *)friendInfo {
NSFetchRequest *req = [[NSFetchRequest alloc] initWithEntityName:@"Friend"];
NSString *atributeName = @"identifier";
NSString *valueName = [[friendInfo objectForKey:@"id"] stringFromMD5];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K like %@",atributeName,valueName ];
req.predicate = predicate;
req.fetchLimit = 1;
NSError *requestError = nil;
NSArray *tmp = [self.managedObjectContext executeFetchRequest:req error:&requestError];
if (tmp && tmp.count >0) {
Friend *friend = [tmp objectAtIndex:0];
friend.name = [friendInfo objectForKey:@"name"];
friend.identifier = [NSString stringWithFormat:@"%@",[[friendInfo objectForKey:@"id"] stringFromMD5]];
[self saveContext];
return;
}
Friend *friend =
[NSEntityDescription insertNewObjectForEntityForName:@"Friend"
inManagedObjectContext:self.managedObjectContext];
friend.name = [friendInfo objectForKey:@"name"];
friend.identifier = [friendInfo objectForKey:@"id"];
friend.noOfMessagesReceived = [NSNumber numberWithInt:0];
friend.email = @"";
friend.selected = [NSNumber numberWithBool:NO];
friend.frooiFriend = [NSNumber numberWithBool:NO];
}
但是第二次运行代码时谓词不匹配任何结果。我相信这是 NSPredicate 的问题。
下面是为 Friend 生成的代码:
@interface Friend : NSManagedObject
@property (nonatomic, retain) NSString * email;
@property (nonatomic, retain) NSNumber * frooiFriend;
@property (nonatomic, retain) NSString * identifier;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * noOfMessagesReceived;
@property (nonatomic, retain) NSData * profileImage;
@property (nonatomic, retain) NSNumber * selected;
@property (nonatomic, retain) NSNumber * frooliMessagesSentTo;
@end
难道我做错了什么?
谢谢