0

我正在尝试使用以下代码将实体插入或更新(如果存在)到核心数据中:

- (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

难道我做错了什么?

谢谢

4

2 回答 2

3

[friendInfo objectForKey:@"id"]等于[[friendInfo objectForKey:@"id"] stringFromMD5]? _

如果不是:这是您的问题,因为您正在设置friend.identifier = [friendInfo objectForKey:@"id"];一个新朋友,但您搜索朋友的谓词使用[[friendInfo objectForKey:@"id"] stringFromMD5].

于 2012-07-20T14:48:06.600 回答
0

尝试使用这个谓词:

[NSPredicate predicateWithFormat:@"%@ MATCHES[cd] '.*%@.*'",atributeName,valueName ];

这不是最好的性能,但它确实有效。之后您可以提高性能。

于 2012-07-20T14:52:34.107 回答