2012-04-25 82 views
1

目前,我編輯了一個將Exercise對象添加到NSMutableArray的委託函數。但是,我不想添加重複的對象,相反,如果對象已經在數組中,我只想簡單地訪問該特定對象。將對象插入到NSMutableArray

這裏是我的代碼:

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

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
    NSString *str = cell.textLabel.text; // Retrieves the string of the selected cell. 

    Exercise *exerciseView = [[Exercise alloc] initWithExerciseName:str]; 
    WorkoutManager *workoutManager = [WorkoutManager sharedInstance]; 

    if (![[workoutManager exercises] containsObject:exerciseView]) { 
     [[workoutManager exercises] insertObject:exerciseView atIndex:0]; 
     [self presentModalViewController:exerciseView animated:YES]; 
     NSLog(@"%@", [workoutManager exercises]); 
    } 
    else { 
     [self presentModalViewController:exerciseView animated:YES]; 
     NSLog(@"%@", [workoutManager exercises]); 
    } 
} 

我認爲這將工作,但是,當我跑我的代碼和NSLogged我的陣列,它表明,當我點擊了同一細胞,創建兩個單獨的對象。任何幫助?

回答

2

我會說這是您的罪魁禍首:

Exercise *exerciseView = [[Exercise alloc] initWithExerciseName:str]; 

您正在創建一個新的對象,每次所以在技術上,它不是在數組中。 containsObject方法只是遍歷數組,並在每個對象上調用isEqual。我沒有測試過這個,但理論上,在您的自定義運動對象中,您可以覆蓋isEqual方法來比較練習名稱屬性,如果匹配則返回true。看到,當你使用containsObject時,一切都必須匹配,因此即使所有屬性都相同,objectid也不會。

,而不必查看你的鍛鍊實現簡單的解決辦法:

Exercise *exerciseView = nil; 

For(Exercise *exercise in [[WorkoutManager sharedInstance] exercises]){ 
    if(exercise.exerciseName == str) { 
     exerciseView = exercise; 
     break; 
    } 
} 

if(exerciseView == nil) { 
    exerciseView = [[Exercise alloc] initWithExerciseName:str]; 
    [[workoutManager exercises] insertObject:exerciseView atIndex:0]; 
} 

[self presentModalViewController:exerciseView animated:YES]; 

希望這有助於解釋爲什麼它的發生。我沒有測試這個代碼,因爲有一些缺失的部分,但你應該明白。玩的開心!

3

每次調用

Exercise *exerciseView = [[Exercise alloc] initWithExerciseName:str]; 

它創建一個新的(不同的)exerciseView對象。因此,儘管練習名稱可能與練習列表中練習對象的名稱相同,但它是一個全新的對象,因此當您撥打containsObject時,結果將始終爲假,並且您的新對象將被添加到數組中。

也許你應該將NSString exerciseName的列表存儲在你的鍛鍊管理器中?

0
WorkoutManager *workoutManager = [WorkoutManager sharedInstance]; 

Exercise *temp = [[Exercise alloc] initWithExerciseName:str]; 
for(id temp1 in workoutManager) 
{ 
    if([temp isKindOfClass:[Exercise class]]) 
    { 
     NSLog(@"YES"); 
     // You Can Access your same object here if array has already same object 
    } 
} 

[temp release]; 
[workoutManager release]; 

希望,這將幫助你....