Note that there are some explanatory texts on larger screens.

plurals
  1. POCan a struct property be retrieved by its string name in Objective-C?
    primarykey
    data
    text
    <p>I have an object which has a property which is a struct like the following:</p> <pre><code>struct someStruct{ float32 x, y; }; </code></pre> <p>And what I'd like to do is invoke the getter for that struct property via a string:</p> <pre><code>id returnValue = [theObject performSelector:NSSelectorFromString(@"thePropertyName")]; </code></pre> <p>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... </p> <p>Any ideas how returnValue can be coaxed back into a struct? Thanks!</p> <p>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:</p> <pre><code>StructType s = ((StructType(*)(id, SEL, NSString*))objc_msgSend_stret)(theObject, NSSelectorFromString(@"thePropertyName"), nil); </code></pre> <p>Edit 2: A fairly detailed look at the issue can be found <a href="http://www.sealiesoftware.com/blog/archive/2008/10/30/objc_explain_objc_msgSend_stret.html" rel="nofollow">here</a>.</p> <p>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):</p> <pre><code>NSValue* thisVal = [NSValue valueWithBytes: &amp;thisStruct objCType: @encode(struct StructType)]; [theObject setValue:thisVal forKey:@"thePropertyName"]; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload