开发者

UIBarButtonItem causes "Unrecognized selector sent to instance"

I call an instance to a class in my main.m to my Controls.m class but it seems to be giving me a "Unrecognized selector sent to instance" error. Any idea what I am doing wrong here? Every time I hit the button it just crashes, but isn't Controls.m set to self in this code? It shouldn't have trouble finding the test selector action.开发者_运维百科

Main.m

- (void)loadView {
    Controls *ct = [[Controls alloc] init];
    [ct addControls];
    [ct release];
}

Controls.m

- (void)addControls {
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, mv.frame.size.height-60, mv.frame.size.width, 40)];
    UIBarButtonItem *barBtnDataOverlay = [[UIBarButtonItem alloc] initWithTitle:@"Test Button" style:UIBarButtonSystemItemAction target:self action:@selector(test)];
    NSArray *toolbarButtons = [[NSArray alloc] initWithObjects:barBtnDataOverlay, nil];
    toolbar.items = toolbarButtons;
    [mv addSubview:toolbar];
    [barBtnDataOverlay release];
    [toolbar release];
 }

- (void)test {
    NSLog(@"TEST button hit");
}


ct will be dealloced by [ct release] as no retain is left. Try to add a ct retin property to your class to keep it around.

In class definition:

@property(nonatomic, retain) Controls *ct;

In your implementation:

@synthesize ct;

...

Change your loadView to something like:

- (void)loadView {
    self.ct = [[Controls alloc] init];
    [self.ct addControls];
    [self.ct release];
}

Or even neater:

- (void)loadView {
    self.ct = [[[Controls alloc] init] autorelease];
    [self.ct addControls];
}

You should also release ct somewhere like in viewDidUnload

- (void)viewDidUnLoad {
    self.ct = nil;
}

BTW, is this in a UIViewController class? then the loadView method should probably assign the view instance variable. If you look in the documentation for UIViewController you will see this:

If you override this method in order to create your views manually, you should do so and assign the root view of your hierarchy to the view property.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜