iphone-使用块从数组中获取子数组会让人感到困惑
我有一个对象数组(json对象) 每个对象都具有以下性质:iphone-使用块从数组中获取子数组会让人感到困惑,iphone,json,nsarray,objective-c-blocks,Iphone,Json,Nsarray,Objective C Blocks,我有一个对象数组(json对象) 每个对象都具有以下性质: { author = "<null>"; category = { "created_at" = "2011-02-06T18:11:39Z"; id = 4; name = lawyers; }; "created_at" = "<null>";
{
author = "<null>";
category = {
"created_at" = "2011-02-06T18:11:39Z";
id = 4;
name = lawyers;
};
"created_at" = "<null>";
id = 693;
"mobile_user_id" = "<null>";
"rating_count" = 0;
status = 1;
text = "A brain walks into a bar and says, \"I'll have a pint of beer please. \"The barman looks at him and says \"Sorry, I can't serve you.\" \"Why not?\" asks the brain. \"You're already out of your head.\"";
title = "A brain goes to a local bar";
}
{
作者=”;
类别={
“创建于”=“2011-02-06T18:11:39Z”;
id=4;
姓名=律师;
};
“已在“=”处创建”;
id=693;
“移动用户id=”;
“评级计数”=0;
状态=1;
text=“一个大脑走进一家酒吧,说:”我要一品脱啤酒。\”酒吧招待看着他说,“对不起,我不能为你服务。\”“为什么不呢?”大脑问。“你已经疯了。”;
title=“大脑进入本地酒吧”;
}
从这些对象数组中,我想找到其类别id为4的对象,并生成一个子数组
有人能帮我使用块并从数组中获取子数组吗?我猜“使用块”是指使用类似NSArray的方法
- (NSIndexSet *)indexesOfObjectsPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate
那看起来像
NSIndexSet *indexes = [yourArray indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
return (BOOL)([[obj valueForKeyPath:@"category.id"] intValue] == 4);
}];
NSArray *filteredArray = [yourArray objectsAtIndexes:indexes];
这是您要求的,但我更愿意使用filteredarrayingpredicate:
如下:
NSPredicate *pred = [NSPredicate predicateWithFormat:@"category.id = %@", [NSNumber numberWithInt:4]];
NSArray *filteredArray = [yourArray filteredArrayUsingPredicate:pred];
一些博客说使用块而不是谓词。为什么要使用“谓词”来获取子数组?您的块代码抛出错误“无效转换初始化整数'int',预期的块指针”,我的json数据有什么问题吗?我的项目使用的目标OS<4.0,因此我不能使用块。我得到“无效转换初始化整数'int',预期的块指针”,我们的比较有什么问题吗?我写块的时候有点快。。。我编辑了答案。