I am using two buttons. I want to access these two buttons object from two different function.-
(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
button1= [UIButton buttonWithType:UIButtonTypeRoundedRect] ;
button2= [UIButton buttonWithType:UIButtonTypeRoundedRect] ;
button1.frame = CGRectMake(50, 50, 100, 30);
button2.frame = CGRectMake(160, 50, 100, 30);
}
return self;
}
And My functions are foo() and bar()开发者_运维百科. In these functions i am using button1 and button2. But it is not working.
First of all, I would suggest creating your buttons using Interface Builder and connecting them to IBOutlets in your controller. Then you can define accessor methods to allow you to access those buttons from functions/methods outside the controller (or use @synthesize to have them defined automatically). You'll want to be careful not to break encapsulation too much. What exactly are you trying to do with your functions?
EDIT: As I mentioned in the comments below, I've now figured out what the problem is. You need to retain the buttons, like this:
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
button1= [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
button2= [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
button1.frame = CGRectMake(50, 50, 100, 30);
button2.frame = CGRectMake(160, 50, 100, 30);
}
return self;
}
加载中,请稍侯......
精彩评论