Home > DeveloperSection > Forums > How to sort object with property in NSArray.
Norman Reedus
Norman Reedus

Total Post:45

Points:315
Posted on    February-12-2015 6:56 AM

 iPhone iPhone  Ios 
Ratings:


 1 Reply(s)
 607  View(s)
Rate this:
How to sort object with property in NSArray.


Elena Glibart
Elena Glibart

Total Post:35

Points:128
Posted on    February-12-2015 6:58 AM

@interface Person : NSObject

@property (nonatomic, retain) NSString *Name;

@property (nonatomic, retain) NSString *City;

@property (nonatomic, retain) NSString *Country;

@end

 

 

 

Person *p1=[Person alloc]init];

p1.Name=@Anil;

p1.City=@Uttarpradesh;

p1.Country=@India;

 

Person *p2=[Person alloc]init];

p2.Name=@Rakesh;

p2.City=@Uttarpradesh;

p2.Country=@India;

 

Person *p3=[Person alloc]init];

p3.Name=@Mayank;

p3.City=@Uttarpradesh;

p3.Country=@India;

 

 NSArray *UnSortedArray=[NSArray arrayWithObjects:p1,p2,p3, nil];

 

   NSArray * sortedArray=nil;

   Bool  isUseCaseInsensitiveCompare=false;

    @try

    {

    NSSortDescriptor *valueDescriptor = nil;

    if(isUseCaseInsensitiveCompare)

    {

 valueDescriptor= [[NSSortDescriptor alloc] initWithKey:@Name ascending:YES selector:@selector(caseInsensitiveCompare:)];

    }

    else{

       valueDescriptor= [[NSSortDescriptor alloc] initWithKey:@Name ascending:YES]; 

    }

    NSMutableArray * descriptors = [NSMutableArray arrayWithObject:valueDescriptor];

    sortedArray = [UnSortedArray sortedArrayUsingDescriptors:descriptors ];

    }

    @catch (NSException *ex) {

        NSLog(@"%@",ex.reason);

    }


Don't want to miss updates? Please click the below button!

Follow MindStick