Objective c - NSMutableSet unique object property

后端 未结 3 1235
北恋
北恋 2020-12-17 10:25

In my app I have a class Person with personId property.
Now I need some data structure to hold a bunch of unique Person objects (u

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-17 11:08

    You shouldn't need to worry about this when you're adding items to an array. As long as you're adding a unique object each time, the properties of the object shouldn't matter.

    If you're worried about this and want to be doubly sure, use NSMutableSet instead (unless you need to maintain order of each object).

    Update

    You could use a predicate to check that an object with the same value does not exist before adding it. This would work fine with both NSMutableArray and NSMutableSet.

    //create array
    NSMutableArray *array = [[NSMutableArray alloc] init];
    
    //create person
    Person *newPerson = [[Person alloc] init];
    
    //add person
    [array addObject:newPerson]
    
    //check new object exists
    if([[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"personID == %@", [newPerson personID]]] count] == 0)
    {
        //add object
        [array addObject:newPerson];
    }
    

    Very rough pseudocode but hopefully you get the gist :)

提交回复
热议问题