views:

217

answers:

2

Hi All,

As before, I have User and Friend entities, One User to Many Friend(s).

I would like to be able to check to see if I have already previously added a Friend (whilst at this point only knowing the name of the potential new Friend at the time). So

NSString *name = @"Bob";
Bool exists = NO;
for(Friend *friend in user.friends)
{
      if([friend.name isEqualToString:name])
           exists = YES;
}
if(!exists)
{
    //add user
}

The only way I can see to do that is to iterate through all Friend objects and check against an attribute to see if its in there, and if after all iterations it finds no match, add it.

Is there a better way?

A: 

NSPredicate

see also this question

Ahmed Kotb
+1  A: 

Here is a different way:

BOOL exists = ([[user.friends filteredSetUsingPredicate:[NSPredicate predicateWithFormat:@"name == %@",name]] count] > 0);

Also, you should break early if you do it your way:

for(Friend *friend in user.friends)
{
    if([friend.name isEqualToString:name]) {
        exists = YES;
        break;
    }
}
gerry3
thank you again - I am learning alot today :-)
mootymoots