创建了一个列表应用,只要按按钮就可以添加字符串到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];
}