添加字符串到NSMutable数组中

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

NSString *name = _noteField.text;
试试NSString *name = [NSString stringWithString:_noteField.text];