如何断言嵌套对象iOS

时间:2019-06-13 05:48:18

标签: ios objective-c nspredicate

我试图断言嵌套对象的值,这里是嵌套对象的结构。

@interface APContact : NSObject
@property (nullable, nonatomic, strong) NSArray <APPhone *> *phones;
@end

@interface APPhone : NSObject
@property (nullable, nonatomic, strong) NSString *number;
@end

我试图像这样在下面的代码块中进行断言。 我要断言number字符串。怎么做

for (APContact *contact in duplucateDataArray) {
    NSMutableArray *countArray = [[NSMutableArray alloc] init];
    NSPredicate *morningAttendees  = [NSPredicate predicateWithFormat:@"SELF.%K.%K MATCHES %@",@"phones[0]",@"number", contact.phones[0].number];
    NSArray <APContact*> *predicateContact = [duplucateDataArray filteredArrayUsingPredicate:morningAttendees];
    NSLog(@"predicate contact%@",predicateContact);
}

在上面的代码上运行时,低于下面的异常

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<APContact 0x2824da6d0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key phones[0].'
 Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do regex matching on object (
    "+91 88815 12534"
).

任何建议都会受到赞赏。

2 个答案:

答案 0 :(得分:1)

删除电话[0],因为错误提示您无法使用电话[0],APContact拥有按键电话。

在行下面使用-

 NSPredicate *morningAttendees  = [NSPredicate predicateWithFormat:@"SELF.%K.%K MATCHES %@",@"phones",@"number", contact.phones[0].number];

答案 1 :(得分:0)

MATCHES替换为LIKE

MATCHES假定您的参数是正则表达式,LIKE假定您的参数是带有通配符的字符串。 source

此外,在使用嵌套谓词时,请使用ANYSOMEALL运算符。

NSPredicate *morningAttendees  = [NSPredicate predicateWithFormat:@"ANY phones.number LIKE %@",contact.phones[0].number];