检查NSMutableArray是否具有特定的Object

时间:2015-01-01 14:23:02

标签: ios objective-c nsmutablearray

我试图在向对象添加对象之前检查NSMutableArray是否具有特定对象,如果存在则不添加。

我查看了很多帖子,解释了如何做到这一点,设法像这样实现它,但它总是让我对象“不存在”,虽然我已经添加了它!

 //get row details into FieldLables Object
            AllItemsFieldNames *FieldLabels = feedItems[row];

            // object to hold single row detailes
            AllItemsFieldNames *SelectedRowDetails = [[AllItemsFieldNames alloc] init];
            SelectedRowDetails.item_name = FieldLabels.item_name;
            //SelectedRowDetails.item_img = FieldLabels.item_img;
            SelectedRowDetails.item_price = FieldLabels.item_price;

            //NSLog(@"item has been added %@", SelectedRowDetails.item_name);
            //NSLog(@"shopcartLength %lu", (unsigned long)SelectedFieldsNames.count);

            if([SelectedFieldsNames containsObject:SelectedRowDetails])
                {
                    NSLog(@"Already Exists!");
                }
            else
            {
                NSLog(@"Doesn't Exist!");
                [SelectedFieldsNames addObject:SelectedRowDetails];
            }

我可以将NSMutableArray中的所有对象显示到一个表中,我需要在上面的代码中做的就是停止添加重复的对象。

2 个答案:

答案 0 :(得分:3)

NSArray文档中列出的第一个方法"查询数组"是containsObject:。如果它无效,则表明您的isEqual:实施不正确。请务必遵循文档中的说明:

  

如果两个对象相等,则它们必须具有相同的哈希值。这个   如果你定义isEqual:在a中,最后一点尤为重要   子类并打算将该子类的实例放入   采集。确保您还在子类中定义哈希。

您也可以考虑使用NSSet,因为您无法添加重复项。当然,这还需要isEqual:的工作版本。

答案 1 :(得分:-1)

集由唯一元素组成,因此这是删除数组中所有重复项的便捷方法。 这里有一些样本,

NSMutableArray*array=[[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4", nil];
    [array addObject:@"4"]; 
    NSMutableSet*chk=[[NSMutableSet alloc ]initWithArray:array]; //finally initialize NSMutableArray   to NSMutableSet
    array= [[NSMutableArray alloc] initWithArray:[[chk allObjects] sortedArrayUsingSelector:@selector(compare:)]]; //after assign NSMutableSet to your NSMutableArray and sort your array,because sets are unordered.
    NSLog(@"%@",array);//1,2,3,4
相关问题