NSMutableArray check if object already exists

前端 未结 9 1389
傲寒
傲寒 2020-12-25 10:17

I am not sure how to go about this. I have an NSMutableArray (addList) which holds all the items to be added to my datasource NSMutableArray.

I now

9条回答
  •  礼貌的吻别
    2020-12-25 10:34

    Did you try indexOfObject:?

    -(void)doneClicked{
        for (Item *item in addList){
            if([appDelegate.list indexOfObject:item] == NSNotFound){
                [appDelegate insertItem:item];
            }
    }
    

    UPDATE: You have a logical mistake, not mistake in code. assume the first array is ['a', 'b', 'c'], and the second is ['a', 'x', 'y', 'z']. When you iterate with 'a' through the second array it won't add 'a' to second array in the first iteration (compare 'a' with 'a') but will add during the second (compare 'a' with 'x'). That is why you should implement isEqual: method (see below) in your 'Item' object and use the code above.

    - (BOOL)isEqual:(id)anObject {
        if ([anObject isKindOfClass:[Item class]])
            return ([self.iName isEqualToString:((Item *)anObject).iName]);
        else
            return NO;
    }
    

提交回复
热议问题