添加字串到NSMutable數組中

來源:互聯網
上載者:User

問題描述:建立了一個列表應用,只要按按鈕就可以添加字串到mutable數組中。不過My Code運行之後,點擊按鈕只有最後的數組添加成功了。[plain]  - (IBAction)notebutton:(UIButton *)sender {       NSMutableArray *mystr = [[NSMutableArray alloc] init];     NSString *name = _noteField.text;     [mystr addObject:name];     [self.tableView reloadData];  }   解決方案:這是因為,你每次點擊這個按鈕的時候都會重新建立NSMutableArray 對象[plain] - (IBAction)notebutton:(UIButton *)sender { NSMutableArray *mystr = [[NSMutableArray alloc] init];   如何解決?你只需要將*mystr聲明放到標頭檔中,作為屬性或私人變數來定義。如[plain]  @interface yourClass:NSObject   {       NSMutableArray  *mystr;  }  @end   在.m的init方法中來初始化這個NSMutableArray[plain]  @implementation yourClass    -(id)init {      if (self=[super init]) {            mystr=[[[NSMutableArray alloc] initWithCapacity:0] autorelease];      }  }  @end   做完這兩步,你就可以直接在  - (IBAction)notebutton:(UIButton *)sender {     NSString *name = _noteField.text;     [mystr addObject:name];     [self.tableView reloadData];  }    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.