Note that there are some explanatory texts on larger screens.

plurals
  1. POObj-C introspection: how to avoid casting all the time?
    primarykey
    data
    text
    <p> Hello all, I've been working on some enumeration routines in Objective-C that perform object introspection. In particular, I'm fast enumerating an <code>NSSet</code> and making sure that the objects therein belong to class <code>BBBallView</code> (an fairly unfortunate name, I agree) before tweaking their properties and/or calling their methods.</p> <p>In order to make the parser and compiler happy, however, I end up casting the object to its class on every single line; moreover, in order to access its properties, the object's cast has to be in parentheses, otherwise dot notation won't work. This leads to somewhat messy code:</p> <pre class="lang-obj-c prettyprint-override"><code>for (id otherBall in self.gameField.subviews) { if ([otherBall isKindOfClass:[BBBallView class]]) { if ( !((BBBallView *)otherBall).isEnlarged ) { CGRect otherFrame = ((BBBallView *)otherBall).frame; /* ... */ } } } </code></pre> <p>Is there any way to tell the compiler something like "at this point I know that <code>otherBall</code> is a <code>BBBallView</code>, so stop telling me it doesn't respond to these selectors and properties"? That way, one could just write:</p> <pre class="lang-obj-c prettyprint-override"><code>for (id otherBall in self.gameField.subviews) { if ([otherBall isKindOfClass:[BBBallView class]]) { if ( !otherBall.isEnlarged ) { CGRect otherFrame = otherBall.frame; /* ... */ } } } </code></pre> <p>and so on.</p> <p>I tried <code>otherBall = (BBBallView *)otherBall</code> but "fast enumeration variables can't be modified in ARC by default". Changing the enumeration variable to <code>__strong id</code> fixes it, but doesn't help the fact that any subsequent line gives out errors such as "property <code>isEnlarged</code> not found on object of type 'const __strong id'", so I'm back to square one.</p> <p>I'm not even sure why exactly this happens: shouldn't the compiler stay out of the way when an variable is of type <code>id</code>? In any case, the whole ordeal particularly messy in methods that need to perform several calculations on objects' properties, as it quickly becomes unreadable with all those parentheses.</p> <p>Is there any way around this?</p> <p>Thanks in advance!</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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