Create a NSSet from NSArray based on property

前端 未结 5 1854
礼貌的吻别
礼貌的吻别 2021-01-12 04:22

How does one create a NSSet of objects from an array based on a property.

e.g. Array of objects, each with a strong reference to a type pro

5条回答
  •  萌比男神i
    2021-01-12 04:50

    You would use:

    NSSet* mySetWithUniqueItems= [NSSet setWithArray: yourArray];
    

    This should work regardless of the type of objects in your array and would populate the NSSet with only one occurence of any duplicate objects in your array.

    I hope this helps.

    Update: Next best thing: is use concatenation of class name and object property first then use the above method.

    self.concatenatedArray=[NSMutableArray arrayWithCapacity:4];
    
    for (TheClass* object in self.myArray)
        [self.concatenatedArray addObject:[NSString stringWithFormat:@"%@-%@",[object class], object.theProperty]];
    
    self.mySet=[NSSet setWithArray:self.concatenatedArray];
    

    I am not sure what you will use the NSSet output for but you can probably modify the concatenation elements to have the information you need in the NSSet output.

提交回复
热议问题