如何在objective-C中过滤自定义对象

时间:2015-09-28 09:38:13

标签: ios objective-c nsarray nspredicate

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

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

[arrayToFilter filterUsingPredicate:namePredicate];

我想根据姓氏过滤它。例如: 我想要一个数组,其中包含姓氏=" Cena"

的学生的所有详细信息

我试过了:

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

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

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

    [names addObject:studentsObj.LastName];
}

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

我用来获取lastName的代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AdditionsPage</title>
</head>

<body>
<h1>Order state</h1>

Customer name: test<br />
Customer Address: test<br />
Pizza size: 32<br /><br />

<b>Available additions:</b><br/>

<table border="1">
    <tr>
        <td>#</td>
        <td>Addition name</td>
        <td>Addition price</td>
        <td>-</td>
    </tr>


        <tr>
            <td>1</td>
            <td>tomato</td>
            <td>30</td>
            <td><a id="row" value="1" href="/PizzaOrderApp/pizzaorder_add">Add</a></td>
        </tr>

        <tr>
            <td>2</td>
            <td>sausage</td>
            <td>50</td>
            <td><a id="row" value="2" href="/PizzaOrderApp/pizzaorder_add">Add</a></td>
        </tr>

        <tr>
            <td>3</td>
            <td>onion</td>
            <td>20</td>
            <td><a id="row" value="3" href="/PizzaOrderApp/pizzaorder_add">Add</a></td>
        </tr>

        <tr>
            <td>4</td>
            <td>fish</td>
            <td>50</td>
            <td><a id="row" value="4" href="/PizzaOrderApp/pizzaorder_add">Add</a></td>
        </tr>

        <tr>
            <td>5</td>
            <td>green pepper</td>
            <td>40</td>
            <td><a id="row" value="5" href="/PizzaOrderApp/pizzaorder_add">Add</a></td>
        </tr>

</table>      
<br/>

<b>Chosen additions:</b><br/>

<table border="1">



</table>    

</body>

1 个答案:

答案 0 :(得分:2)

将谓词更新为

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

然后

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

仅获取姓氏,

python3 your_file.py