将块回调插入NSMutableDictionary

时间:2014-04-26 22:08:51

标签: ios objective-c nsdictionary objective-c-blocks

我想从网络服务器获取对照片的评论。服务器返回包含注释的数组。是否可以将块而不是注释数组附加到NSMutableDictionary? 我希望块返回注释并将其值插入字典。

我的意思是有人这样认为(但它会产生编译错误):

 NSArray* (^commentsBlock)(id responseObject) = ^(id responseObject){
        return responseObject;
 };


[self fetchCommentsForNode:[fileInfo objectForKey:@"nid"]
                                       success: commentsBlock];

            VDPhoto *photo = [VDPhoto photoWithProperties:
                              @{@"imageView": imageview,
                                @"title": [fileInfo objectForKey:@"title"],
                                @"comments" : commentsBlock,
                                }];

            [photos addObject:photo];

2 个答案:

答案 0 :(得分:1)

除了评论中的讨论之外,您可能想要做这样的事情......

fetchCommentsForNode:success:的块中内联一些内容 - 更新字典:

NSMutableDictionary *properties = [@{@"imageView": imageview,
                                         @"title": [fileInfo objectForKey:@"title"]} mutableCopy];

[self fetchCommentsForNode:[fileInfo objectForKey:@"nid"] success:^(id responseObject){
       properties[@"comments"] = responseObject;
       return responseObject;
}];

VDPhoto *photo = [VDPhoto photoWithProperties:properties];

[photos addObject:photo];

您要做的就是确保@property方法中VDPhoto properties init中的strongcopy,而不是success然后您可以查看字典,并在调用@property (nonatomic, copy) NSArray *comments块后设置注释。

编辑:

更好的选择是将VDPhoto属性添加到fetchCommentsForNode:,然后在VDPhoto *photo = [VDPhoto photoWithProperties:@{@"imageView": imageview, @"title": [fileInfo objectForKey:@"title"]}]; [photos addObject:photo]; [self fetchCommentsForNode:[fileInfo objectForKey:@"nid"] success:^(id responseObject){ photo.comments = responseObject; return responseObject; }]; 上设置结果:

{{1}}

答案 1 :(得分:0)

不,一个物体不能成为"另一个对象。你想要做的是让块在字典中插入结果数组,而不是"成为"结果数组。