使用NSMutablearray数据更改UILabel中的文本

时间:2011-09-22 01:47:25

标签: iphone ios nsmutablearray uilabel

我试图在点击按钮时用数组中的文本更改UILabel的文本,但它没有做任何事情。

@interface Test01AppDelegate : NSObject <UIApplicationDelegate> {
UILabel *helloLabel;
UIButton *hellobutton;
NSMutableArray *madWords;
}

@property (nonatomic, retain) IBOutlet UIWindow *window; 
@property (nonatomic, retain) IBOutlet UIButton *hellowButton;
@property (nonatomic, retain) IBOutlet UILabel *hellowLabel;

@property (nonatomic, retain) NSMutableArray *madWords;

- (void) madArrays;
- (IBAction)helloYall;

@end

#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];

}

我可以用

设置helloLabel文本
@"some text here";

它工作正常。此外,我尝试将“madArrays”方法复制到“helloYall”方法中,但仍然无法正常工作。正如我所说的,我可以手动设置文本并且它可以工作,但我想从数组中提取信息。最后,我想循环遍历数组以获取每个按钮按下的文本,但一次一步。感谢。

3 个答案:

答案 0 :(得分:3)

您永远不会创建madWords数组。你需要添加:

self.madWords = [NSMutableArray array];

位于顶部:

 - (void) madArrays {

可能是一个好地方。其他可能很好的地方是我的类init方法或视图控制器viewWillAppear方法。

答案 1 :(得分:0)

   // 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];
}

答案 2 :(得分:0)

当您来填充它时,madArrays仍然是nil。在某些时候,你需要像[self setMadArrays:[[NSMutableArray alloc] init]];这样的东西。另外,在调用madArrays之前,请不要忘记在dealloc中发布super,因为您会发生内存泄漏。