I have an object which has a property which is a struct like the following:
struct someStruct{
float32 x, y;
};
And what I’d like to do is invoke the getter for that struct property via a string:
id returnValue = [theObject performSelector:NSSelectorFromString(@"thePropertyName")];
But as you can see “performSelector:” returns an object, not a struct. I’ve tried every way of casting I could think of, to no avail, which makes me think I’m missing something – perhaps something easy…
Any ideas how returnValue can be coaxed back into a struct? Thanks!
Edit:
Whoever the original responder was (he’s since deleted his post for some reason) – you were right: The following, based on your answer, works:
StructType s = ((StructType(*)(id, SEL, NSString*))objc_msgSend_stret)(theObject, NSSelectorFromString(@"thePropertyName"), nil);
Edit 2: A fairly detailed look at the issue can be found here.
Edit 3: For symmetry’s sake, here’s how to set a struct property by its string name (note that this is exactly how the accepted answer accomplishes setting, whereas my problem required the slightly different approach for the getter mentioned in the first edit above):
NSValue* thisVal = [NSValue valueWithBytes: &thisStruct objCType: @encode(struct StructType)];
[theObject setValue:thisVal forKey:@"thePropertyName"];
You can do this using Key Value Coding by wrapping the
structinside anNSValue(and unwrapping it when it is returned). Consider a simple class with a struct property, as shown below:We can then wrap and unwrap the
structin anNSValueinstance to pass it to and from the KVC methods. Here is an example of setting the value of the struct using KVC:To get the struct as a return value, use
NSValue‘sgetValue:method: