• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

使用Objective-cBlock

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

在函数声明中,使用Block(在c#里,应该叫匿名委托),在处理简单事件时,显得十分的方便,先看一段代码:

//在.h中定义函数声明
-(void)processJsonObject:(id) obj atIndex:(NSInteger)index DictionaryObjectUsingBlock:(void (^)(id key, id value))dictionaryHandler NS_AVAILABLE(10_6, 4_0);


//在.m中定义实现
-(void)processJsonObject:(id) obj atIndex:(NSInteger)index DictionaryObjectUsingBlock:(void (^)(id key, id value))dictionaryHandler NS_AVAILABLE(10_6, 4_0)
{
    if ([obj isKindOfClass:[NSDictionary class]])
    {
        NSString *key = [obj allKeys][index];
        id obj2 = [obj objectForKey:key];

        dictionaryHandler(key, obj2);
    }    
}

//调用函数

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
//如果要在block中,修改局部变量,需要使用__block修饰符 __block
id<JsonDelegate> delegate = NULL; [self processJsonObject:_obj atIndex:indexPath.row DictionaryObjectUsingBlock:^(id key, id value) {
delegate = [[JsonDict alloc] initWithKey:key andValue:value];
... }
]; cell.delegate = delegate; cell.textLabel.text = [delegate key]; cell.detailTextLabel.text = [delegate detailText]; ...

return cell; }

这样,就不用单独声明一个函数作为委托方法了,直接声明就可以了

 

这个例子是用UITableView按层级方式浏览Json数据,如果希望下载完整的代码,请访问 https://github.com/iihe602/View-Json-Tree-2


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
objective-c下面int和NSData数据互相转换的方法发布时间:2022-07-12
下一篇:
【Objective-C 篇】 ☞ 学前准备发布时间:2022-07-12
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap