Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 899
Sonny G Avatar asked Dec 10 '25 23:12

Sonny G


1 Answers

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 ]; 
like image 187
Rocker Avatar answered Dec 12 '25 14:12

Rocker