NSPredicate通过对象数组过滤

时间:2014-09-23 18:42:56

标签: ios xcode nspredicate predicate

这是我的自定义NSObject类:

@interface personObject : NSObject

@property (nonatomic, copy) NSString *personName;
@property (nonatomic, copy) UIImage *personPhoto;

@property BOOL invited;

- (id) initWithName: (NSString *) personName Photo: (UIImage *) photo Invited: (BOOL *) invited;

@end

@implementation personObject
@synthesize personName = _personName;
@synthesize personPhoto = _personPhoto;
@synthesize invited = _invited;

 - (id) initWithName:(NSString *)personName Photo:(UIImage *)photo Invited:(BOOL *)invited{
    self = [super init];
    if (self) {
        self.personName = personName;
        self.personPhoto = photo;
        self.invited = invited;
    }
    return self;
}

@end

我在viewDidLoad中初始化三个人物。 现在我试过

[NSPredicate predicateWithFormat:@"personName beginswith[c], searchText];

但是我得到了一个错误 -

-[personObject copyWithZone:]: unrecognized selector sent to instance 0x109684330'

所以我尝试了这个:

- (void) filterContententForSearchText: (NSString *) searchText scope:(NSString *) scope{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K beginsWith[c]  %@",_currentPerson.personName, searchText ];
    self.searchArray = [self.peopleArray filteredArrayUsingPredicate:predicate];
}

所以我尝试设置

_currentPerson  = [self.peopleArray objectAtIndex.row];

在tableViewcellForRowAtIndexPath方法中并使用它代替。但我得到了一个不同的错误 - 原因:

'[<personObject 0x109524750> valueForUndefinedKey:]: this class is not key value coding-compliant for the key Paul Smith.'

当我开始输入搜索栏时,会发生这两个错误。

继承行方法...如何在搜索数组中将单元格文本设置为currentPerson.personName

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    personObject *currentPerson = [self.peopleArray objectAtIndex:indexPath.row];

    self.personCell = (personCell *) [self.tableView dequeueReusableCellWithIdentifier:@"personCell"];

    if (tableView == self.searchDisplayController.searchResultsTableView) {
        self.personCell.nameLabel.text = [self.searchArray objectAtIndex:indexPath.row];
    }
    else{
        self.personCell.nameLabel.text = currentPerson.personName;
    }
    return _personCell;
}

1 个答案:

答案 0 :(得分:0)

您需要检查personName密钥而不是_currentPerson.personName作为密钥。当您提供_currentPerson.personName时,它会将其作为密钥并将其视为整个密钥,应该是{{1但是你不需要它,你只能将NSCoding作为字符串传递,它将通过@"personName"。将上面的函数替换为下面的

keyValueCoding