問題描述:做了一個清單 App,希望每按一次按鈕就把輸入框的字串加進 mutable 陣列。但程式跑起來後,點擊按鈕的結果只剩下最後一次的值,前面的都消失了。
- (IBAction)notebutton:(UIButton *)sender {
NSMutableArray *mystr = [[NSMutableArray alloc] init]; // ← 問題在這一行
NSString *name = _noteField.text;
[mystr addObject:name];
[self.tableView reloadData];
}
陣列的宣告位置錯了。這行程式碼寫在 IBAction 方法內部,代表每次點擊按鈕都會重新配置一個全新的空 NSMutableArray,前一次加入的內容自然就跟著舊物件一起被回收。這不是 NSMutableArray 的問題,而是物件生命週期(scope)的問題。
第一步:在標頭檔中宣告為成員變數(或屬性)。
@interface yourClass : NSObject
{
NSMutableArray *mystr;
}
@end
第二步:在 init 方法中做一次性的初始化。
@implementation yourClass
- (id)init {
if (self = [super init]) {
mystr = [[NSMutableArray alloc] initWithCapacity:0];
}
return self;
}
@end
第三步:之後 IBAction 裡就不再建立新物件,直接使用既有的陣列。
- (IBAction)notebutton:(UIButton *)sender {
NSString *name = _noteField.text;
[mystr addObject:name];
[self.tableView reloadData];
}
用 ARC 的話,直接宣告成 strong 屬性更簡潔,而且可以搭配延遲載入(lazy loading),確保它永遠不會是 nil:
@interface yourClass ()
@property (nonatomic, strong) NSMutableArray *mystr;
@end
@implementation yourClass
- (NSMutableArray *)mystr {
if (!_mystr) {
_mystr = [NSMutableArray array];
}
return _mystr;
}
- (IBAction)notebutton:(UIButton *)sender {
[_mystr addObject:_noteField.text];
[self.tableView reloadData];
}
@end
空字串也要擋。 使用者直接按確認而不輸入任何內容時,_noteField.text 會是空字串甚至 nil。往陣列加入 nil 會直接引發 NSInvalidArgumentException 崩潰,所以要先判斷。
NSString *name = _noteField.text;
if (name.length == 0) return;
[_mystr addObject:name];
reloadData 之前要確認 dataSource 綁定正確。 如果按下按鈕後陣列確實有增加,畫面卻沒更新,問題通常不在這段程式碼,而在 numberOfRowsInSection 或 cellForRowAtIndexPath 讀取的是另一份資料來源。