检查对象是否已经存在

时间:2022-04-03 04:28:16

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.

我不知道该怎么做。我有一个NSMutableArray (addList),它包含要添加到我的数据源NSMutableArray中的所有项。

I now want to check if the object to be added from the addList array already exists in the datasource array. If it does not exist add the item, if exists ignore.

我现在要检查从addList数组中添加的对象是否已经存在于数据源数组中。如果它不存在,添加条目,如果存在,则忽略。

Both the objects have a string variable called iName which i want to compare.

这两个对象都有一个名为iName的字符串变量,我想对其进行比较。

Here is my code snippet

这是我的代码片段

-(void)doneClicked{
    for (Item *item in addList){
        /*
        Here i want to loop through the datasource array 
        */
        for(Item *existingItem in appDelegate.list){
            if([existingItem.iName isEqualToString:item.iName]){
                // Do not add
            }
            else{
                [appDelegate insertItem:item];
            } 
        }
}

But i find the item to be added even if it exists.

但我发现即使它存在,也要添加这个项目。

What am i doing wrong ?

我做错了什么?

9 个解决方案

#1


69  

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

NSArray中有一个非常有用的方法,即containsObject。

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

#2


39  

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.

然后遍历添加数组并插入项。

#3


22  

Use NSPredicate.

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

#4


5  

Did you try indexOfObject:?

你试试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.

更新:您有一个逻辑错误,而不是代码错误。假设第一个数组是[a,b,c的),第二是[' a ',' x ',' y ',' z ']。当你在第二个数组中迭代“a”时,它不会在第一次迭代中向第二个数组添加“a”(比较“a”和“a”),而是在第二次迭代中添加(比较“a”和“x”)。这就是为什么要在“Item”对象中实现isEqual:方法(见下文),并使用上面的代码。

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

#5


4  

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.

看看NSSet。您可以添加对象,对象只有在对象是唯一的时候才会被添加。可以从NSArray创建NSSet,也可以反过来创建NSSet。

#6


2  

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

您可以覆盖对象上的isEquals和散列,以便根据iName属性的比较返回一个YES / NO。

Once you have that you can use...

一旦你有,你可以使用…

- (void)removeObjectsInArray:(NSArray *)otherArray

To clean the list before adding all the remaining objects.

要在添加所有剩余对象之前清除列表。

#7


2  

NR4TR said correctly but i think one break statement is sufficient

NR4TR说得对,但我认为一个中断声明就足够了


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

#8


1  

Convert Lowercase and Trim whitespace and then check..

转换小写和装饰空格,然后检查。

[string lowercaseString];  

and

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

#9


1  

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.

比较addList的第一个对象和appDelegate。如果列表的第一个对象不相等,则插入addList的对象。逻辑是错误的,您应该将一个addList的对象与每个appDelegate进行比较。的对象列表。

#1


69  

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

NSArray中有一个非常有用的方法,即containsObject。

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

#2


39  

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.

然后遍历添加数组并插入项。

#3


22  

Use NSPredicate.

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

#4


5  

Did you try indexOfObject:?

你试试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.

更新:您有一个逻辑错误,而不是代码错误。假设第一个数组是[a,b,c的),第二是[' a ',' x ',' y ',' z ']。当你在第二个数组中迭代“a”时,它不会在第一次迭代中向第二个数组添加“a”(比较“a”和“a”),而是在第二次迭代中添加(比较“a”和“x”)。这就是为什么要在“Item”对象中实现isEqual:方法(见下文),并使用上面的代码。

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

#5


4  

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.

看看NSSet。您可以添加对象,对象只有在对象是唯一的时候才会被添加。可以从NSArray创建NSSet,也可以反过来创建NSSet。

#6


2  

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

您可以覆盖对象上的isEquals和散列,以便根据iName属性的比较返回一个YES / NO。

Once you have that you can use...

一旦你有,你可以使用…

- (void)removeObjectsInArray:(NSArray *)otherArray

To clean the list before adding all the remaining objects.

要在添加所有剩余对象之前清除列表。

#7


2  

NR4TR said correctly but i think one break statement is sufficient

NR4TR说得对,但我认为一个中断声明就足够了


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

#8


1  

Convert Lowercase and Trim whitespace and then check..

转换小写和装饰空格,然后检查。

[string lowercaseString];  

and

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

#9


1  

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.

比较addList的第一个对象和appDelegate。如果列表的第一个对象不相等,则插入addList的对象。逻辑是错误的,您应该将一个addList的对象与每个appDelegate进行比较。的对象列表。