Search code examples
objective-cinitalloc

alloc and init in a subclass


I have subclassed UIView and provided my own drawRect, which works fine. However I added these methods to my subclass:

 - (id) alloc
 {
    NSLog(@"Alloc");
    return [super alloc];
 }

 - (id) init
 {
    NSLog(@"Init");
    if (self = [super init])
        flashWhite = true;
    return self;
 }

I thought that whenever an object of the subclass is created (which happens through Interface Builder), the alloc and init methods would get called. However the object IS created, but my init and alloc don't get called. Shouldn't this happen to ensure proper initialization?

Also, building produces a warning that UIView may not respond to 'alloc' - doesn't it have to inherit this from NSObject, or how could a UIView be properly created?

My objective in the above was that my subclassed view would be able to do custom initialization after IB got it created.


Solution

  • init is not the designated initializer for UIView; initWithFrame: is. If you override initWithFrame:, it should get called, but init never gets called by UIView.