簡體   English   中英

檢查NSMutableArray是否具有特定的對象

[英]Check if NSMutableArray has a specific Object

我試圖檢查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中的所有對象顯示到一個表中,在上面的代碼中我需要做的就是停止添加重復的對象。

NSArray文檔中“查詢數組”部分下列出的第一個方法是containsObject: :。 如果不起作用,則表明您對isEqual:的實現不正確。 確保遵循文檔中的說明:

如果兩個對象相等,則它們必須具有相同的哈希值。 如果您在子類中定義isEqual:並打算將該子類的實例放入集合中,則最后一點特別重要。 確保您還在子類中定義哈希。

您也可以考慮使用NSSet因為您不能向其中添加重復項。 當然,這也需要isEqual:的工作版本。

集由唯一的元素組成,因此這是刪除數組中所有重復項的便捷方法。 這里有一些樣品,

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM