I’m still trying to get my head around how selectors and dynamic typing work in objective c. I’m essentially trying to implement this method (shown below in python/pseudocode, same thing really :P)
def isInArray(value, array, test):
for item in array:
if test(item) == value:
return True
return False
test = lambda obj: obj.property
My intended objective-c code was:
+ (BOOL)value:(id)value:
isInArray:(NSMutableArray *)array
usingSelector:(SEL)selector {
for (id item in array) {
if (value == [item selector]) {
return YES;
}
}
return NO;
}
However, this throws a compile error, complaining that I”m comparing two pointer types (id and SEL) in the if statement.
Shouldn’t that if statement be comparing the object value with the object returned from running SEL selector on the object arritem? In other words, why does it think that it’s comparing an object with a SEL (I don’t see what would be returning a SEL there)
Checkout
performSelectorinNSObject. The conditional would look like,By using
Key Value Coding(KVC), your code could become even simpler. Say you have an array namedpeople, where each person is an object of the classPerson. APersonhasfirstNameandlastNameproperties, and you want to get all people whose first name matches"John"from thepeoplearray. You could get an array of all first names, and then lookup the name"John"in that array.Even though we’re using
valueForKey, it’s actually making a call to thefirstNamemethod, and not directly accessing the value.