Let’s say I have an NSArray called myArray of NSStrings (@"a0",@"a1",@"a2")
Then in a fast enumeration I loop into my array to build properties according to that NSStrings. I’ve got a problem accessing that properties.
I’m trying something like that :
@property (nonatomic) float a0propertyLow;
@property (nonatomic) float a0propertyHigh;
@property (nonatomic) float a1propertyLow;
@property (nonatomic) float a1propertyHigh;
..
.. etc.
for (NSString *aPos in myArray) {
NSString *low = [NSString stringWithFormat:@"%@propertyLow",aPos];
NSString *high = [NSString stringWithFormat:@"%@propertyHigh",aPos];
SEL lowSel = NSSelectorFromString(low);
SEL highSel = NSSelectorFromString(high);
if ([self respondsToSelector:lowSel]&&[self respondsToSelector:highSel]) {
id sumPartOne = [self performSelector:lowSel];
id sumPartTwo = [self performSelector:highSel];
float bla = (float)sumPartOne + (float)sumPartTwo;
}
}
I know my code is wrong but I don’t know how to make it work.
My problem is that lowSel and highSel are getters which returns float but the perform selector method returns id which is ok for an object but not for floats.
So, how can I access my float getters with variable names ? I’m sure answer must be simple but it seems that my mind is looking for something complicated (and which obviously doesn’t work) so I’m asking for help 🙂
Thank you very much for your help
You can’t use
performSelector:to call a method that returns a scalar value. The documentation forperformSelector:clearly says what you have to do:An
NSInvocationis a little more complex to set up but more flexible regarding arguments and return types.In your case, it is probably easier to use Key-Value Coding instead:
takes the return type into account and will automatically wrap the
floatin anNSNumber.