我正在尝试提交此对象的数组:
MyObject.h
@interface MyObject : NSObject
@property (assign) int id_object;
@property (nonatomic, strong) NSString *name;
@end
所以例如在我的firstArray中我有一些MyObject:
MyObject *ob1 = [[MyObject alloc] init];
[ob1 setId_Object:1;
[ob1 setName:@"Carl"];
MyObject *ob2 = [[MyObject alloc] init];
[ob2 setId_Object:2;
[ob2 setName:@"Carl"];
MyObject *ob3 = [[MyObject alloc] init];
[ob3 setId_Object:3;
[ob3 setName:@"Carl"];
NSArray *firstArray = [[NSArray alloc] initWithObjects:ob1,ob2,ob3,nil];
然后我希望用NSPredicate过滤这个数组,并使用NSNumber数组,如下所示:
NSArray *secondArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],[NSNumber numberWithInt:2],nil];
我试过这个:
NSArray *filteredObject = [firstArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"id_object IN %@",secondArray]];
但过滤后的对象是空的,我该怎么做?
答案 0 :(得分:0)
检查一下,
NSArray *filteredObject = [questionSections filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.Carl contains %@ OR self.Carl contains %@ ",@"1",@"2"]];
EX: -
NSArray* questionSections=[[NSArray alloc] initWithObjects:[[NSDictionary alloc] initWithObjectsAndKeys:
@"List 3 rooms in your house?",@"name",@"301q.png",@"questionpicture",nil],[[NSDictionary alloc] initWithObjectsAndKeys:@"Name a commonbird?",@"name",@"202q.png",@"questionpicture",nil], nil];
NSArray *filteredObject = [questionSections filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.questionpicture contains %@ OR self.questionpicture contains %@ ",@"2",@"3"]];
NSLog(@"%@",filteredObject);
O / P: -
(
{
name = "List 3 rooms in your house?";
questionpicture = "301q.png";
},
{
name = "Name a common bird?";
questionpicture = "202q.png";
}
)
答案 1 :(得分:0)
尝试替换
@property (nonatomic, copy) NSNumber* id_object;
@property (nonatomic, copy) NSString *name;
而不是
@property (assign) int id_object;
@property (nonatomic, strong) NSString *name;
答案 2 :(得分:0)
似乎是你的测试用例错了。我不认为你的setId_object在用NSNumber调用它时会做你的想法;
[ob1 setId_object:[NSNumber numberWithInt:1]];
NSLog(@"%d", ob1.id_object);
> 391
[ob1 setId_object:1];
NSLog(@"%d", ob1.id_object);
> 1
替换初始化会使您的测试用例运行正常。
编辑:我的测试用例,cut'n'pasted;MyObject *ob1 = [[MyObject alloc] init]; ob1.id_object = 1; [ob1 setName:@"Carl"];
MyObject *ob2 = [[MyObject alloc] init]; ob2.id_object = 2; [ob2 setName:@"Carl"];
MyObject *ob3 = [[MyObject alloc] init]; ob3.id_object = 3; [ob3 setName:@"Carl"];
NSArray *firstArray = [[NSArray alloc] initWithObjects:ob1,ob2,ob3,nil];
NSArray *secondArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],[NSNumber numberWithInt:2],nil];
NSArray *filteredObject = [firstArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"id_object IN %@",secondArray]];
NSLog(@"%@", filteredObject);
>>> <MyObject: 0x100110350> {1,"Carl"}
>>> <MyObject: 0x1001104b0> {2,"Carl"}