NSMutableArray check if object already exists

你。 提交于 2019-11-30 03:07:10
Black Tiger

There is a very useful method for this in NSArray i.e. containsObject.

NSArray *array;
array = [NSArray arrayWithObjects: @"Nicola", @"Margherita",                                       @"Luciano", @"Silvia", nil];
if ([array containsObject: @"Nicola"]) // YES
{
    // Do something
}

I found a solution, may not be the most efficient of all, but atleast works

NSMutableArray *add=[[NSMutableArray alloc]init];

for (Item *item in addList){
        if ([appDelegate.list containsObject:item])
            {}
        else
            [add addObject:item];
}

Then I iterate over the add array and insert items.

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];
}

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;
}

Have a look at NSSet. You can add objects and the object will only be added if the object is unique. You can create a NSSet from an NSArray or vise versa.

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.

NR4TR said correctly but i think one break statement is sufficient


if([existingItem.iName isEqualToString:item.iName]){
                // Do not add
break;
            }
 
Rams

Convert Lowercase and Trim whitespace and then check..

[string lowercaseString];  

and

NSString *trim = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!