开发者

Returning an instance of a class within its self

开发者 https://www.devze.com 2023-03-14 02:05 出处:网络
i am trying to write a UIToolbar subclass and am having issues. This is the first time i have truly tried to sub class anything so forgive me if it is something stupid. I cant work out how to return a

i am trying to write a UIToolbar subclass and am having issues. This is the first time i have truly tried to sub class anything so forgive me if it is something stupid. I cant work out how to return an instance of the class from within its self. eg

keyboardToolBar *toolbar;
@property (nonatomic, retain) keyboardToolBar *t开发者_运维问答oolbar;
toolbar = [[keyboardToolBar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 50)
-(keyboardToolBar*)initWithFrame:(CGRect)frame{

keyboardToolBar *keyboard = [[keyboardToolBar alloc] initWithFrame:frame];<--how can i do this
//do stuff with keyboard
return keyboard;
}

I assume the above will be stuck in an endless loop of calling init which calls init and so on, so how do you return an instance of a class from within its own init method or is there a better way of doing this.

thanks

darc


There are many things that are not clear here. Are you trying to create convenience method? in which case you should call it keyboardToolbarWithFrame: and implement it like

+ (id)keyboardToolbarWithFrame:(CGRect)frame {
    return [[[self alloc] initWithFrame:frame] autorelease];
}

Note the + sign indicating that it is a class method. This will give you an autoreleased instance of your class.

Now if you were just trying to class its super class for necessary initialization, you can just remove the method. It will call the super class' initWithFrame: method. But usually your own implementation will be something like this,

- (id)initWithFrame:(CGRect)frame {
    self = [super init];
    if ( self ) {
        // Do your class initializations here.
    }

    return self;
}


Did you check the sample projects here: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIToolbar_Class/Reference/Reference.html

0

精彩评论

暂无评论...
验证码 换一张
取 消