以下来自互联网的代码似乎表现不正常。 NSPredicate返回对象值而不是该对象的属性值,该对象是一个字符串。 (见下面的输出)。有没有人见过这个?
如果您认为这是正确的,那么我该如何打印字符串值?
// Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property NSString *firstName;
@property NSString *lastName;
@property NSNumber *age;
@end
// ViewControll.m
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray *firstNames = @[ @"Alice", @"Bob", @"Charlie", @"Quentin" ];
NSArray *lastNames = @[ @"Smith", @"Jones", @"Smith", @"Alberts" ];
NSArray *ages = @[ @24, @27, @33, @31 ];
NSMutableArray *people = [NSMutableArray array];
[firstNames enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Person *person = [[Person alloc] init];
person.firstName = firstNames[idx];
person.lastName = lastNames[idx];
person.age = ages[idx];
[people addObject:person];
}];
NSPredicate *bobPredicate = [NSPredicate predicateWithFormat:@"firstName = 'Bob'"];
NSPredicate *smithPredicate = [NSPredicate predicateWithFormat:@"lastName = %@", @"Smith"];
NSPredicate *thirtiesPredicate = [NSPredicate predicateWithFormat:@"age >= 30"];
// ["Bob Jones"]
NSLog(@"Bobs: %@", [people filteredArrayUsingPredicate:bobPredicate]);
// ["Alice Smith", "Charlie Smith"]
NSLog(@"Smiths: %@", [people filteredArrayUsingPredicate:smithPredicate]);
// ["Charlie Smith", "Quentin Alberts"]
NSLog(@"30's: %@", [people filteredArrayUsingPredicate:thirtiesPredicate]);
}
@end
输出
2014-08-12 17:51:31.526 NSPredicate[41013:60b] Bobs: (
"<Person: 0x10931c720>"
)
2014-08-12 17:51:31.527 NSPredicate[41013:60b] Smiths: (
"<Person: 0x10931cf60>",
"<Person: 0x10931c110>"
)
2014-08-12 17:51:31.527 NSPredicate[41013:60b] 30's: (
"<Person: 0x10931c110>",
"<Person: 0x10931ca30>"
)
答案 0 :(得分:1)
NSPredicate的行为应该如此。
NSPredicate将返回符合谓词规范的每个对象。它将不返回您正在寻找的属性值。
如果您认为这是正确的,那么我该如何打印字符串值?
简单:NSPredicate返回具有所需属性的对象,因此只需询问每个对象的属性!
NSPredicate *thirtiesPredicate = [NSPredicate predicateWithFormat:@"age >= 30"];
// ["Charlie Smith", "Quentin Alberts"]
NSArray *peopleOver30 = [people filteredArrayUsingPredicate:thirtiesPredicate];
for (int i = 0; i < peopleOver30.count; i++) {
Person *person = peopleOver30[i];
NSLog(@"First Name: %@, Last Name: %@, Age: %@", person.firstName, person.lastName, person.age);
}
预期产出:
2014-08-12 17:51:31.526 NSPredicate[41013:60b] First Name: Charlie Last Name: Smith Age: 33
2014-08-12 17:51:31.526 NSPredicate[41013:60b] First Name: Quentin Last Name: Alberts Age: 31
答案 1 :(得分:0)
当您使用自定义类来保存数据时。 当您尝试使用NSLog打印值时,它将打印person对象的地址 您必须在Person类中使用description方法来打印所有属性
-(NSString *)description{
return @"FirstName: %@, LastName: %@, E-mail: %@",
_firstName, _lastName, _email;
}
以下是相同的参考问题点击here!