Moving isa pointers is a problem if your subclasses have instance variables different from those specified in SomeClassView . Please note that your nib file has an object of type SomeClassView , which means that when you load the nib file, the nib loader will select an object of this type and cancel it from the nib file. Changing the isa pointer to [SubViewClass class] temporarily does not make it an object of type SubViewClass per se, since what the nib loader selects is a SomeClassView object.
However, I do not think that this is a reliable and automatic way to use nib files containing objects whose types must be changed when loading nib.
What you can do is have your SomeClassView objects SomeClassView delegate that conforms to some protocol. This protocol will define behaviors in SomeClassView that can potentially be extended. For instance,
@protocol SomeClassViewDelegate @optional - (void)someClassViewDidAwakeFromNib:(SomeClassView *)someClassView; @end
Instead of subclassing SomeClassView , you have arbitrary objects that execute any custom behavior that you currently have in SubClassView . For instance,
@interface SubClassViewBehaviour : NSObject <SomeClassViewDelegate> … @end @implementation SubClassViewBehaviour - (void)someClassViewDidAwakeFromNib:(SomeClassView *)someClassView { // whatever behaviour is currently in -[SubClassView foo] } @end
A SubClassViewBehaviour object A will be created in the code and set as the owner of the nib files when loading the nib file or any other IB proxy object, for that matter. SomeClassView will have a delegate output connected to the owner / proxy object file, and itd will call the delegate methods in the appropriate places. For instance,
@implementation SomeClassView - (void)awakeFromNib { SEL didAwakeFromNib = @selector(someClassViewDidAwakeFromNib:); if ([[self delegate] respondsToSelector:didAwakeFromNib]) { [[self delegate] performSelector:didAwakeFromNib withObject:self]; } } @end
One more note: your code is currently losing an object of the view, because two objects are created: one through +alloc in your code, and the other through loading nib. You assign the last self , therefore, created with +alloc . In addition, I believe that you missed the super call in your third piece of code.
user557219
source share