0

I have a custom object which contains data as:

@interface Students : NSObject
{

}
@property (nonatomic,strong) NSString   *ID;
@property (nonatomic,strong) NSString   *FirstName;
@property (nonatomic,strong) NSString   *MiddleName;
@property (nonatomic,strong) NSString   *LastN

I want to filter it according to the last name. For example: I want an array which contains all the details of students having last name="Cena"

I tried this:

NSMutableArray *arrayToFilter = self.studentList;
NSString *nameformatString = @"LastName contains[c] a";
NSPredicate *namePredicate = [NSPredicate predicateWithFormat:nameformatString];

[arrayToFilter filterUsingPredicate:namePredicate];

When I run my app I am getting this error and my app crashes:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: 
'[< Students 0x7fd25e102d20> valueForUndefinedKey:]: 
this class is not key value coding-compliant for the key a.'

I am only able to get last name in array but I know this is wrong. How can I sort the custom object based on last name.

Code I am using to get lastName:

  names = [[NSMutableArray alloc]init];
for (int i = 0; i < [self.studentList count] ; i++)
{
    Students * studentsObj = (Students*)[self.studentList objectAtIndex:i];

    [names addObject:studentsObj.LastName];
}

1 Answer 1

1

Update the predicate to ,

NSString *textToMatch = @"a";
NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"LastN CONTAINS[cd] %@", textToMatch];

then

NSMutableArray *arrayToFilter = self.studentList;
NSArray *filteredArray = [arrayToFilter filteredArrayUsingPredicate:namePredicate];

for getting last name only,

NSArray *lastNames = [filteredArray valueForKey:@"LastN"];
NSArray *sortedArray = [lastNames sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
Sign up to request clarification or add additional context in comments.

4 Comments

Or, in other words, the property is called LastN and not LastName.
In predicate the property name was spelled wrong. and using valueForKey:@"LastN" will return all last names in an array.
@Akhilrajtr now again this error is occurring ... after getting sorted array i am again applying same predicate the i am getting eror
@user5370850 Sorted array is of type NSString so the predicate should be @"SELF CONTAINS[cd] %@"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.