添加字符串到NSMutable数组中
原问题来自于CSDN问答频道,详细解决方案见:http://ask.csdn.net/questions/1723
问题描述:
创建了一个列表应用,只要按按钮就可以添加字符串到mutable
数组中。不过我的代码运行之后,点击按钮只有最后的数组添加成功了。
- (IBAction)notebutton:(UIButton *)sender { NSMutableArray *mystr = [[NSMutableArray alloc] init]; NSString *name = _noteField.text; [mystr addObject:name]; [self.tableView reloadData];}
解决方案:
这是因为,你每次点击这个按钮的时候都会重新创建NSMutableArray 对象
- (IBAction)notebutton:(UIButton *)sender { NSMutableArray *mystr = [[NSMutableArray alloc] init];
如何解决?
你只需要将*mystr声明放到头文件中,作为属性或私有变量来定义。如
@interface yourClass:NSObject { NSMutableArray *mystr;}@end
在.m的init方法中来初始化这个NSMutableArray
@implementation yourClass-(id)init { if (self=[super init]) { mystr=[[[NSMutableArray alloc] initWithCapacity:0] autorelease]; }}@end
做完这两步,你就可以直接在你的IBAction中来使用了
- (IBAction)notebutton:(UIButton *)sender { NSString *name = _noteField.text; [mystr addObject:name]; [self.tableView reloadData];}