2012-04-25 84 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]; 

希望,这将帮助你....