构建nspredicate时EXC_BAD_ACCESS

我正在计算生日和今天之间的月数。 有了这个数字,我正在构建一个谓词来从核心数据中获取对象。 虽然正确计算了月数(如日志所示),但在构建谓词时我得到了EXC_BAD_ACCESS。

这是我的代码:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSUInteger unitFlags = NSMonthCalendarUnit; NSDateComponents *components = [gregorian components:unitFlags fromDate:birthdate toDate:today options:0]; int months = [components month]; NSLog(@"months: %ld", (long)months); NSPredicate *pred = [NSPredicate predicateWithFormat:@"(alter_min_monat > %@)", months]; 

为什么会这样?

问题是占位符。 %@不应与int一起使用,而应使用%d

所以这一行:

 NSPredicate *pred = [NSPredicate predicateWithFormat:@"(alter_min_monat > %@)", months]; 

应该:

 NSPredicate *pred = [NSPredicate predicateWithFormat:@"(alter_min_monat > %d)", months]; 

其他链接信息: 字符串编程指南:字符串格式说明符

Interesting Posts