Change text in UILabel with NSMutablearray data
I'm trying to change the text of a UILabel with text from an array upon a button click, but it doesn't do anything.
@interface Test01AppDelegate : NSObject <UIApplicationDelegate> {
UILabel *helloLabel;
UIButton *hellobutton;
NSMutableArray *madWords;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonat开发者_如何学运维omic, retain) IBOutlet UIButton *hellowButton;
@property (nonatomic, retain) IBOutlet UILabel *hellowLabel;
@property (nonatomic, retain) NSMutableArray *madWords;
- (void) madArrays;
- (IBAction)helloYall;
@end
and
#import "Test01AppDelegate.h"
@implementation Test01AppDelegate
@synthesize window = _window;
@synthesize hellowButton;
@synthesize hellowLabel;
@synthesize madWords;
- (void) madArrays {
[madWords addObject:@"Part A"];
[madWords addObject:@"Part B"];
[madWords addObject:@"Part C"];
[madWords addObject:@"Part D"];
}
- (IBAction)helloYall {
[self madArrays];
self.hellowLabel.text = [madWords objectAtIndex:0];
}
I can set the helloLabel text with
@"some text here";
and it works fine. Also, I tried copying the "madArrays" method into the "helloYall" method and it still didn't work. As I said, I can manually set the text and it works, but I'd like to pull the info from an array. Eventually, I'd like to loop through the array to grab the text on each button press, but one step at a time. Thanks.
You never create the madWords
array. You need to add:
self.madWords = [NSMutableArray array];
at the top of:
- (void) madArrays {
would probably be a good place. Other possibly good places would be i the class init
method or the view controller viewWillAppear
method.
// Or you can try this in your init Method:
//first allocate the ivar
- (void)myInitMethod {
madArrays = [[NSMutableArray]alloc]init];
}
//then you can do anything directly to the ivar or throughout de setter
- (void)doAnythingWithiVar {
// do your stuff
}
//when you are done you can dealloc your ivar
- (void)dealloc {
[madArrays release];
[super dealloc];
}
It looks like madArrays
is still nil
when you come to populate it. At some point you need something like [self setMadArrays:[[NSMutableArray alloc] init]];
. Also, don't forget to release madArrays
in the dealloc
before calling super
as you'll have a memory leak.
精彩评论