Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>IFF</strong> your subclass adds only methods and <em>not</em> any storage (i.e., ivars) to the superclass, then you can use a semi-black-magic technique* called "isa-swizzling". Rob Napier <a href="https://stackoverflow.com/questions/6035021/trapping-objective-c-classes/6035695#6035695">mentions it</a>, and links to <a href="http://deusty.blogspot.com/2008/05/casting-subclassing-and-isa-field.html" rel="nofollow noreferrer">a blog post</a> that explains it all.</p> <p>Each Objective-C instance has a chunk of storage in memory for its instance variables, but the implementation of the <em>methods</em> is all kept in another place, in the storage for the class object. The runtime uses an instance's <code>isa</code> pointer to get at the class object.</p> <p>It is therefore possible, as demonstrated in the linked blog post, to transform an instance of one class into another <strong>provided they have exactly the same fields</strong>. As Rob warns, you <em>cannot</em> add ivars, only change the methods.</p> <p>Casting <code>(MyDerivedClass *)instanceOfSuperclass</code> only has an effect at compile-time. All it does is make the compiler happy when it is comparing types: it doesn't affect the runtime lookup of methods, so your <code>instanceOfSuperclass</code> will still <em>act</em> like a <code>Superclass</code>.</p> <p><strike>EDIT: Just as a final thought, since we're already talking about dangerous techniques, perhaps you could create a helper class that would hold the ivars that you want to add to the subclass.</strike> Whew, now I've really gone mad!</p> <p><sub>I have never done this myself; I am only reporting a technique that may be useful to you. <em>Please</em> pay attention to all the warnings you see when this is discussed.</sub></p> <hr> <p>*Used for <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueObserving/Articles/KVOImplementation.html%23//apple_ref/doc/uid/20002307-BAJEAIEE" rel="nofollow noreferrer">KVO</a>, interestingly.</p>
    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.
    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