-1

我有一个自定义对象叫MyContact,里面有两个参数,一个是name(NSString),另一个是phoneArray(NSArray)。我生成了一个 MyContact 数组并使用带有“phoneArray contains %@”的 NSPredicate 进行过滤,我得到了空结果,但是当我使用“name contains %@”进行过滤时,我可以得到正确的结果。我不知道为什么。以下是我的演示代码!

@interface MyContact : NSObject

@property (nonatomic, retain) NSString *name;

@property (nonatomic, retain) NSArray *phoneArray;

@end

@autoreleasepool {

    NSMutableArray *myContacts = [[NSMutableArray alloc] init];

    MyContact *contact1 = [[MyContact alloc] init];
    contact1.name = @"will mo";
    contact1.phoneArray = [NSArray arrayWithObjects:@"138761", nil];
    [myContacts addObject:contact1];
    [contact1 release];

    MyContact *contact2 = [[MyContact alloc] init];
    contact2.name = @"robert jiang";
    contact2.phoneArray = [NSArray arrayWithObjects:@"13554227",   @"876368268", nil];
    [myContacts addObject:contact2];
    [contact2 release];

    MyContact *contact3 = [[MyContact alloc] init];
    contact3.name = @"watson song";
    contact3.phoneArray = [NSArray arrayWithObjects:@"73514637", @"6216738", nil];
    [myContacts addObject:contact3];
    [contact3 release];

    MyContact *contact4 = [[MyContact alloc] init];
    contact4.name = @"marco sch";
    contact4.phoneArray = [NSArray arrayWithObjects:@"42437845", nil];
    [myContacts addObject:contact4];
    [contact4 release];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"phone contains %@", @"24"];
    NSArray *resultArray = [myContacts filteredArrayUsingPredicate:predicate];
    NSLog(@"%@", resultArray);

    [myContacts release];
}
4

1 回答 1

1

“phoneArray”是一个字符串数组。要检查任何数组元素是否包含给定字符串,请使用

[NSPredicate predicateWithFormat:@"ANY phoneArray CONTAINS %@", @"24"];
于 2013-07-07T14:10:40.497 回答