iosobjective-cnsarraynsset

NSSet with string property from array of objects


I have an array of somethings, I'd like to make a set from an NSString property on this object:

@protocol something<NSObject>

@property(nonatomic, readonly) NSString *Id;

@end

I have an array of somethings:

NSArray<id<something>> *arrayOfSomethings;

I'd like to get a NSSet of the Id properties:

NSSet<NSString *> *idSet = ?; // Calculate from arrayOfSomethings.

How do I do this? Thanks


Solution

  • You can use valueForKey: to create an array that contains your ids and then use that to create an NSSet

    NSSet<NSString *> *idSet = [NSSet setWithArray:[arrayOfSomethings valueForKey:@"id"]];