accessing a method from a button within a class?
#import "GameObject.h"
#import "Definitions.h"
@implementation GameObject
@synthesize owner;
@synthesize state;
@synthesize mirrored;
@synthesize button;
@synthesize switcher;
- (id) init {
if ( self = [super init] ) {
[self setOwner: EmptyField];
button = [UIButton buttonWithType:UIButtonTypeCustom];
[self setSwitcher: FALSE];
}
return self;
}
- (UIButton*) display{
button.frame = CGRectMake(0, 0, GO_Width, GO_Height);
[button setBackgroundImage:[UIImage imageNamed:BlueStone] forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed:)
forControlEvents:UIControlEventTouchUpInside];
return button;
}
-(void)buttonPressed:(id) sender {
//...
}
}
- (void) dealloc {
[super dealloc];
}
@en开发者_如何转开发d
Hi!
i would like to know if the above is possible somehow within a class (in my case it is called GameObject) or if i HAVE to have the button call a methode in the viewcontroller... the above results with the app crashing.
i would call display within a loop on the viewcontroller and id like to change some of the GameObjects instance variables within buttonPressed. Also id like to change some other stuff by calling some other methods from within buttonPressed but i think that will be the lesser of my problems ;)
oh, btw: i do all that programmaticaly! so no interface builder on this one.
also id like to know how i can pass some variables to the buttonPressed method... cant find it anywhere :( help on this one would be much appreciated ;)
thanks flo
Your app is crashing because of memory management issue.
button = [UIButton buttonWithType:UIButtonTypeCustom]; // wrong
The +buttonWithType:
method is not an +alloc
/-copy
/+new
method, so the return value will be -autorelease
d. But the GameObject is going to be the owner of this button. Therefore, you should -retain
it.
button = [[UIButton buttonWithType:UIButtonTypeCustom] retain]; // correct
(and of course, -release
it in -dealloc
.)
精彩评论