我有一个带有NSString
,UIImage
和BOOL
属性的personObject。我想创建一个只过滤NSString
personObject *person1 = [[personObject alloc]initWithName:@"John Smith" Photo:nil Invited:false];
personObject *person2 = [[personObject alloc]initWithName:@"Peter Smith" Photo:nil Invited:false];
personObject *person3 = [[personObject alloc]initWithName:@"Paul Smith" Photo:nil Invited:false];
[self.peopleArray addObject:person1];
[self.peopleArray addObject:person2];
[self.peopleArray addObject:person3];
- (void) filterContententForSearchText: (NSString *) searchText scope:(NSString *) scope{
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", searchText];
self.searchArray = [self.peopleArray filteredArrayUsingPredicate:predicate];
}
People数组包含personObjects。
答案 0 :(得分:0)
您可以使用
+ (NSPredicate *)predicateWithBlock:(BOOL (^)(id evaluatedObject, NSDictionary *bindings))block
答案 1 :(得分:0)
您应检查name
属性,如果要将其作为子字符串进行搜索,请使用contains
,请参阅此示例:
Class PersonObject:
@interface PersonObject : NSObject
{
NSString* name;
UIImage* img;
BOOL invited;
}
-(id)initWithName:(NSString*)name Photo:(UIImage*)img Invited:(BOOL)invited;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) UIImage *img;
@property (nonatomic, assign, getter=isInvited) BOOL invited;
@end
实现:
#import "PersonObject.h"
@implementation PersonObject
-(id)initWithName:(NSString*)n Photo:(UIImage*)im Invited:(BOOL)i{
if(self = [super init]){
_name=n;
_img=im;
_invited=i;
}
return self;
}
@end
代码:
PersonObject *person1 = [[PersonObject alloc]initWithName:@"John Smith" Photo:nil Invited:false];
PersonObject *person2 = [[PersonObject alloc]initWithName:@"Peter Smith" Photo:nil Invited:false];
PersonObject *person3 = [[PersonObject alloc]initWithName:@"Paul Smith" Photo:nil Invited:false];
[self.peopleArray addObject:person1];
[self.peopleArray addObject:person2];
[self.peopleArray addObject:person3];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains[c] %@", @"Smith"];
self.searchArray = [self.peopleArray filteredArrayUsingPredicate:predicate];
NSLog(@"results: %@", self.searchArray);
输出:
2014-09-22 14:57:31.010 asf[27731:2455623] results: (
"<personObject: 0x7ffdbe301050>",
"<personObject: 0x7ffdbe3010c0>",
"<personObject: 0x7ffdbe3010f0>"
)
希望它有所帮助!