- (IBAction)noteButton:(UIButton *)sender {
NSMutableArray *mystr = [[NSMutableArray alloc] init]; // 每次點擊都新建!
[mystr addObject:_noteField.text];
[self.tableView reloadData];
}
每次點擊都在區域建立新陣列,舊資料立即釋放,TableView 只會顯示最後一次添加的項目。
// .h 或類別擴展
@property (nonatomic, strong) NSMutableArray *notesArray;
// .m
- (instancetype)init {
self = [super init];
if (self) {
_notesArray = [NSMutableArray array];
}
return self;
}
- (IBAction)noteButton:(UIButton *)sender {
NSString *text = _noteField.text;
if (text.length > 0) {
[_notesArray addObject:text];
[_noteField setText:@""];
[self.tableView reloadData];
}
}
// TableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _notesArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// ... 取 _notesArray[indexPath.row] 顯示
}
若需 App 重啟後保留,可在 addObject 後存入 NSUserDefaults 或寫入檔案:
[[NSUserDefaults standardUserDefaults] setObject:_notesArray forKey:@"savedNotes"];
[[NSUserDefaults standardUserDefaults] synchronize];
啟動時從 NSUserDefaults 讀取初始化 _notesArray。