将块保留在字典中 [英] Keep blocks inside a dictionary

查看:124
本文介绍了将块保留在字典中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有自己的方法,将块作为参数。我想跟踪NSDictionary中的那个块。将块添加到字典的最佳方法是什么?

I have my own method that takes a block as an argument. I want to keep track of that block inside an NSDictionary. What is the best way to add the block to the dictionary?

我尝试了这段代码,但在执行下面的行(setObject ...)后,字典仍为空。我认为这是因为该块不是NSObject类型。但是这样做的正确方法是什么?

I tried this code but after executing the line below (setObject...) the dictionary is still empty. I presume that is because the block is not of type NSObject. But what is the right way to do this?

- (void)startSomething:(NSURLRequest*)request block:(void (^)(NSURLResponse*, NSData*, NSError*))handler {

    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];

    [pendingRequests setObject:handler forKey:connection];
}

编辑:

没关系。我不知道我在想什么。 3分:

Never mind. I don't know what I was thinking. 3 points:


  1. 块是objc对象

  2. 错误:setObject应该是setValue

  3. forKey是一个字符串所以它应该是[连接描述]或类似的东西

无论如何我修复了我的问题现在是这样的:

Anyway I fixed my problem now like this:

- (void)startSomething:(NSURLRequest*)request block:(void (^)(NSURLResponse*, NSData*, NSError*))handler {

    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [pendingRequests setValue:handler forKey:[connection description]];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {

        void (^handler)(NSURLResponse*, NSData*, NSError*);
        handler = [pendingRequests valueForKey:[connection description]];
        handler(nil, nil, nil);
    });
}


推荐答案

那仍然没有去工作,或者最多,只会巧合地工作。

That still isn't going to work or, at best, will only work coincidentally.

你需要复制处理程序然后才能将其推入词典。类似于:

You need to copy the handler before shoving it in the dictionary. Something like:

void (^handlerCopy)(NSURLResponse*, NSData*, NSError*) = Block_copy(handler);
[dict setObject:handlerCopy forKey:@"foo"];
Block_release(handlerCopy); // dict will -retain/-release, this balances the copy.

而且,是的,它应该是 setObject:forKey: objectForKey:

And, yes, it should be setObject:forKey: and objectForKey:.

这篇关于将块保留在字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆