ios NSMutableArray 检查对象是否已经存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6291412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:15:56  来源:igfitidea点击:

NSMutableArray check if object already exists

iphoneobjective-ciosnsmutablearray

提问by Neelesh

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 ?

我究竟做错了什么 ?

采纳答案by Neelesh

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.

然后我遍历 add 数组并插入项目。

回答by Black Tiger

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
}

回答by EmptyStack

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

回答by knuku

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”进行比较) ')。这就是为什么你应该isEqual:在你的 'Item' 对象中实现方法(见下文)并使用上面的代码。

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

回答by Charged Neuron

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,反之亦然。

回答by saurabh

NR4TR said correctly but i think one breakstatement is sufficient

NR4TR 说得对,但我认为一个break语句就足够了


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

回答by Simon Lee

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

您可以覆盖对象上的isEqualshash,以便它根据 iName 属性的比较返回 YES / NO。

Once you have that you can use...

一旦你有了它,你就可以使用......

- (void)removeObjectsInArray:(NSArray *)otherArray

To clean the list before adding all the remaining objects.

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

回答by Rams

Convert Lowercase and Trim whitespace and then check..

转换小写和修剪空格,然后检查..

[string lowercaseString];  

and

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

回答by Terence

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.list 的第一个对象,如果它们不相等,则插入 addList 的对象。逻辑是错误的,您应该将一个 addList 的对象与每个 appDelegate.list 的对象进行比较。