NSMutableArray check if object already exists

前端 未结 9 1390
傲寒
傲寒 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:33

    NR4TR said correctly but i think one break statement is sufficient

    
    if([existingItem.iName isEqualToString:item.iName]){
                    // Do not add
    break;
                }
     
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-25 10:37

    Use NSPredicate.

    NSArray *list = [[appDelegate.list copy] autorelease];
    
    for (Item *item in addList) {
    
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"iName MATCHES %@", item.iName];
        NSArray *filteredArray = [list filteredArrayUsingPredicate:predicate];
        if ([filteredArray count] > 0) [appDelegate insertItem:item];
    }
    
    0 讨论(0)
  • 2020-12-25 10:39

    You can override isEquals and hash on the object so that it returns a YES / NO based on the comparison of the iName property.

    Once you have that you can use...

    - (void)removeObjectsInArray:(NSArray *)otherArray
    

    To clean the list before adding all the remaining objects.

    0 讨论(0)
  • 2020-12-25 10:40

    You compare the addList's first object and appDelegate.list's first object, if they are not equal, you insert the addList's object. The logic is wrong, you should compare one addList's object with every appDelegate.list's object.

    0 讨论(0)
  • 2020-12-25 10:49

    Convert Lowercase and Trim whitespace and then check..

    [string lowercaseString];  
    

    and

    NSString *trim = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    0 讨论(0)
提交回复
热议问题