0
votes

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.

3
I should have made alloc a CLASS method - '+ alloc' ratherthan '- alloc - Jonathan Starr
rather than '- alloc' - so when I do that, then my subclass alloc does get called. But I am still confused about init. - Jonathan Starr

3 Answers

1
votes

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.

1
votes

You're right about alloc, it's a class method. UIViews use initWithFrame: for initialisation, so look into overriding that.

0
votes

Apple generally builds their init overrides like this:

-(id)init{
   self = [super init];
    if (self) {
          //Custom Initialization goes here
     }
}

Though the above commenters are correct. initwithFrame: is the designated initializer However, the override as you formatted your question will get you a compiler warning for your trouble.