Search code examples
iosfilternsmutablearrayuniquensorderedset

How to add unique object to nsmutablearray?


I have an NSObject with NSStrings inside. How do I add objects with unique obj.name only to an NSMutableArray? I tried NSOrderedSet but it only works if you add NSString to an array and not objects with NSString inside.

Example.

@@interface MyObject : NSObject
@property (strong, nonatomic) NSString *name;
@end


NSMutableArray *array = {MyObject.name,MyObject.name,MyObject.name};

How do I make sure that no two MyObjects have the same name?


Solution

  • Use NSPredicate for seraching object in NSMutableArray if not present then add it to NSMutableArray. Try this.

      NSArray * filtered = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name = %@", @"MyObject.name"]];
      if(![array count])
            [array addObject:MyObject ];