我正在尝试使用以下代码将实体插入或更新(如果存在)一个实体:
- (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的一个问题。
以下是为朋友生成的代码:
@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
我做错了吗?
由于
答案 0 :(得分:3)
[friendInfo objectForKey:@"id"]
是否等于[[friendInfo objectForKey:@"id"] stringFromMD5]
?
如果不是:这是您的问题,因为您为新朋友设置了friend.identifier = [friendInfo objectForKey:@"id"];
,但您搜索朋友的谓词使用了[[friendInfo objectForKey:@"id"] stringFromMD5]
。
答案 1 :(得分:0)
尝试使用此谓词:
[NSPredicate predicateWithFormat:@"%@ MATCHES[cd] '.*%@.*'",atributeName,valueName ];
这不是最好的表现,但它有效。之后你可以改善表现。