Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 如何从parrent数组创建子数组?_Objective C_Arrays_Parent Child - Fatal编程技术网

Objective c 如何从parrent数组创建子数组?

Objective c 如何从parrent数组创建子数组?,objective-c,arrays,parent-child,Objective C,Arrays,Parent Child,我的应用程序使用多个表视图 它包含一个根视图控制器,该控制器具有一个NSMutableArray,名为mainArray,带有id、父id、标题、副标题和说明 在我的SecondTableViewController中,我需要根据父节点id从主数组创建一个childArray,以便填充tableviewcells 我需要我的childArray1只包含每个家长的id、title、subtitle\u id=1个childArray2只包含每个家长的id、title、subtitle\u id=2

我的应用程序使用多个表视图

它包含一个根视图控制器,该控制器具有一个NSMutableArray,名为mainArray,带有id、父id、标题、副标题和说明

在我的SecondTableViewController中,我需要根据父节点id从主数组创建一个childArray,以便填充tableviewcells

我需要我的childArray1只包含每个家长的id、title、subtitle\u id=1个childArray2只包含每个家长的id、title、subtitle\u id=2,依此类推


有没有一些提示可以这样做

试着用字典,我想这样更好

NSDictionary *parent = @{@"id":@(1),@"title":@"Root",@"subtitle":@"my subtitle",@"description":@"something"};
NSDictionary *child1 = @{@"id":@(2),@"title":@"Child 1",@"subtitle":@"lalalala",@"description":@"something",@"parent":parent};
NSDictionary *child2 = @{@"id":@(3),@"title":@"Child 2",@"subtitle":@"lelelele",@"description":@"something",@"parent":child1};

//so now, you can do something like
child2[@"parent"][@"id"]; // 2
child2[@"parent"][@"parent"][@"title"]; // root

由于JSON指示NSArray包含NSDictionary对象,因此您可以执行以下操作:

NSPredicate *parentPredicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            return evaluatedObject[@"parent_id"] == 1; //set this id to different value to get children of different parent
        }];

NSArray *childArray = [parentArray filteredArrayUsingPredicate:parentPredicate];

您可以将
parent\u id
设置为另一个值,以获取那些
parent\u id
s的子数组。

首先,您考虑过使用NSDictionary吗?处理元素会简单得多,因为您使用的是key->value格式,而不是NSArray中的索引。我愿意接受任何新想法。就像我说的,我是Xcode新手,不一定能找到你。您可以编辑添加mainArray的构建方式吗?这是一个数组的数组?mainArray是一个来自JSON的数组。我会给你一个链接来查看JSON_ecode的输出,谢谢。我使用了NSPredicate方法。