使用Objectivec Block

在函数声明中,使用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

原文地址:https://www.cnblogs.com/iihe602/p/2875730.html