我有一个自定义对象,其中包含以下数据:

@interface Students : NSObject
{

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


我想根据姓氏对其进行过滤。例如:
我想要一个包含姓氏=“ Cena”的学生的所有详细信息的数组

我尝试了这个:

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

[arrayToFilter filterUsingPredicate:namePredicate];


当我运行我的应用程序时,出现此错误,我的应用程序崩溃:

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


我只能在数组中获取姓氏,但我知道这是错误的。如何根据姓氏对自定义对象进行排序。

我用来获取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];
}

最佳答案

将谓词更新为,

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


然后

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


仅用于获得姓氏

NSArray *lastNames = [filteredArray valueForKey:@"LastN"];
NSArray *sortedArray = [lastNames sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

关于ios - 如何在Objective-C中过滤自定义对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32819861/

10-12 14:32