0

我目前有一個函數寫成saveWorkout,它將一個NSMutableArray從一個Singleton類中保存到另一個NSMutableArray。這個函數是第一次運行,但是當我第二次運行它時,它擦除之前存儲在元素0中的內容,並將其替換爲新數組(當用戶單擊表格時收集的字符串集合) 。NSMutableArray覆蓋以前存儲的元素

這裏是我的功能:

-(IBAction)saveWorkout{ 
    WorkoutManager *workoutManager = [WorkoutManager sharedInstance]; 

    [[workoutManager workouts] insertObject: customWorkout atIndex: 0]; 

    NSLog(@"%@", [workoutManager workouts]); 

} 

customWorkout是什麼initialially創建NSMutableArray的(基於用戶點擊了什麼)。因此,如果我的第一個數組由blah1,blah2組成,那麼這兩個值將存儲在訓練數組中。然而,如果我然後點擊blah2,blah 3,訓練數組將有兩個標識數組(blah2,blah3),並且它不保留第一個數組。任何想法爲什麼發生這種情況?

這是我如何形成customWorkout:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
    NSString *str = cell.textLabel.text; 

    [customWorkout insertObject:str atIndex:0]; 

    //Test Code: Prints Array 
    NSLog(@"%@", customWorkout); 
} 

回答

2

我會告訴你,你可以將這個邏輯錯誤....

您使用的是相同的customWorkout對象一遍又一遍,以插入在訓練數組中...(所以它的指針是相同的),而你需要做的是創建一個customWorkout數組的副本,然後將其插入鍛鍊數組中...試試這個,而不是......

[[workoutManager workouts] insertObject: [[customWorkout mutableCopy] autorelease]atIndex: 0]; 

這應該工作,除非你在代碼中做別的事情。

0

[[workoutManager workouts] insertObject: customWorkout atIndex: 0];不復制customWorkout的內容...相反,它只是保留對customWorkout的引用。因此,您的代碼只是將多個引用存儲到同一個對象,最終(無意)在第二次運行時編輯該對象。

您需要:

  • 複製通過copycustomWorkout對象,當你將它存儲在workouts
    OR:指定customWorkout每次
  • 到一個新的NSMutableArray比如你做一個saveWorkout

任一路徑應該不要將您存儲的NSMutableArray修改爲workouts集合。第一種選擇可能在內存管理方面更爲明確......