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;
}
The
foo->barsyntax directly accesses instance variables. You shouldn’t do that. The syntax to access a property is:or:
Accessing a property is always a method call. If you have a property
fooand do@synthesize foo;, the compiler generates a method namedfooandsetFoo:(if the property isn’t readonly).So you should have something like:
Replace
readonlywithcopyif you want the name to be changeable (the reason to usecopyinstead ofretainis 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:
Instead of
[ingredient name]you can also writeingredient.namehere, 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.