user1078065
user1078065

Reputation: 412

ios How to properly use NSPredicate for NSString matching with Core Data?

I'm trying to insert or update(if it exists) an entity into Core Data with the following code:

- (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];
}

But the predicate doesn't match any result when runiing the code the second time. I beleive it's a problem with the NSPredicate.

Here is the code generated for 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

Am I doing something wrong?

Thanks

Upvotes: 0

Views: 538

Answers (2)

Adam
Adam

Reputation: 26917

Try to use this predicate:

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

It's not the best for performance, but it works. You can improve performance afterwards.

Upvotes: 0

tilo
tilo

Reputation: 14169

Is [friendInfo objectForKey:@"id"] equal to [[friendInfo objectForKey:@"id"] stringFromMD5]?

If not: this is your problem, as you are setting friend.identifier = [friendInfo objectForKey:@"id"]; for a new friend, but your predicate for searching for a friend uses [[friendInfo objectForKey:@"id"] stringFromMD5].

Upvotes: 3

Related Questions