How to remove duplicate records / objects from NSArray

 

 

Example code how to remove duplicate records / objects from NSArray and return a NSMutableArray with a unique record set.
Using:
Xcode 4.2.1
Mac OS X 10.7.2
Cocoa
 
First create and execute a fetch request in the example i will use a Address entity a fetchedObjects array will be returned with duplicate streetnames.

NSEntityDescription *entity = [NSEntityDescription 

                                       entityForName:@"Address" inManagedObjectContext:context];

             

NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];

 
 
After executing the executeFetchRequest create a NSSet object which by design can only hold unique objects and set the valueForKey to the field with duplicates.

NSSet *uniqueSet = [NSSet setWithArray:[fetchedObjects valueForKey:@"streetName"]];

   
NSMutableArray *uniqueArray = [NSMutableArray arrayWithArray:[uniqueSet allObjects]];                

 
Create a NSMutableArray and use arrayWithArray and allobjects to create the array with unique streetNames. 
 

 

Comments

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.