Search code examples
iphonecocoa-touchobjective-c++iso

Check for value in NSMutableArray


I have an NSMutableArray in my class containing Ingredient objects. I want to check whether the name property of any of the ingredients matches a string, but I can't get the syntax quite right.

I'm really missing Linq and predictates.

-(BOOL) hasIngredient:(NSString *)ingredientName{
    for (Ingredient *ingredient in ingredients) {
        //if([ingredient isKindOfClass:[Ingredient class]]){
            if ([ingredient->name isEqualToString:ingredientName]) {
                return YES;
            }
        //}
    }
                 return NO;
}

Solution

  • The foo->bar syntax directly accesses instance variables. You shouldn't do that. The syntax to access a property is:

    object.property
    

    or:

    [object property]
    

    Accessing a property is always a method call. If you have a property foo and do @synthesize foo;, the compiler generates a method named foo and setFoo: (if the property isn't readonly).

    So you should have something like:

    @property(nonatomic,readonly) NSString *name;
    

    Replace readonly with copy if you want the name to be changeable (the reason to use copy instead of retain is because you could pass a mutable string and then later modify that mutable string, which would sure yield unexpected results; you avoid that by copying).

    Now your method becomes:

    -(BOOL) hasIngredient:(NSString *)ingredientName{
        for (Ingredient *ingredient in ingredients) {
            if ([[ingredient name] isEqual:ingredientName]) {
                return YES;
            }
        }
        return NO;
    }
    

    Instead of [ingredient name] you can also write ingredient.name here, but I personally like the former better since the later is also used for accessing members of a struct which is "cheap" whereas accessing a property always involves a method call and thus is "more expensive". But that's just a matter of taste.