我有自己的方法,以块为参数.我想跟踪NSDictionary中的那个块.什么是最好的方法来添加到字典的块?
我尝试这个代码,但执行下面的行(setObject …)后,字典仍然是空的.我认为这是因为块不是类型NSObject.但是,这样做的正确方法是什么?
- (void)startSomething:(NSURLRequest*)request block:(void (^)(NSURLResponse*,NSData*,NSError*))handler { NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self]; [pendingRequests setObject:handler forKey:connection]; }
编辑:
没关系.我不知道我在想什么3分:
>块是对象
> Typo:setObject应该是setValue
> forKey是一个字符串,所以应该是[连接描述]或类似的东西
无论如何我现在解决了我的问题:
- (void)startSomething:(NSURLRequest*)request block:(void (^)(NSURLResponse*,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*,NSError*); handler = [pendingRequests valueForKey:[connection description]]; handler(nil,nil,nil); }); }
解决方法
这还不行,或者说,最多只会巧合.
您需要复制处理程序,然后将其拖放到字典中.就像是:
void (^handlerCopy)(NSURLResponse*,NSError*) = Block_copy(handler); [dict setObject:handlerCopy forKey:@"foo"]; Block_release(handlerCopy); // dict will -retain/-release,this balances the copy.
而且,是的,它应该是setObject:forKey:和objectForKey :.