首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS NSMutableArray 按鈕點擊添加字串:陣列需宣告為屬性而非區域變數

     編輯:程式設計綜合問答

錯誤代碼

- (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。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved