我有自己的方法,以块作为参数.我想跟踪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];
}
Run Code Online (Sandbox Code Playgroud)
编辑:
没关系.我不知道我在想什么.3分:
无论如何我现在解决了我的问题:
- (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);
});
}
Run Code Online (Sandbox Code Playgroud) 为了更好地理解块的行为,我一直试图理解这次崩溃背后的原因.我有一个非常简单的类来触发这个崩溃.
@implementation BlockCrashTest
- (void)doSomething
{
dispatch_queue_t queue = dispatch_queue_create("com.queue.test", DISPATCH_QUEUE_SERIAL);
__weak typeof(self) weakSelf = self;
dispatch_block_t block = ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
dispatch_group_t group = dispatch_group_create();
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);
dispatch_group_enter(group);
[strongSelf performSomethingAsync:^{
dispatch_group_leave(group);
}];
if(dispatch_group_wait(group, time) != 0) {
NSLog(@"group already finished");
}
};
dispatch_async(queue, block);
}
- (void)performSomethingAsync:(void(^)(void))completion
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
sleep(5);
completion();
});
}
- (void)dealloc
{
NSLog(@"released object");
}
@end
Run Code Online (Sandbox Code Playgroud)
现在,如果我分配类并简单地调用方法doSomething,
BlockCrashTest *someObject = [[BlockCrashTest alloc] init]; …Run Code Online (Sandbox Code Playgroud) block objective-c grand-central-dispatch ios objective-c-blocks