在nsdictionary中的块? [英] blocks in nsdictionary?
问题描述
所以我将块动作存储到一个nsmutabledictionary,然后当响应回到websocket时回忆它们。这将异步请求转换为块语法。这里是下面的代码:
So I'm storing block actions into a nsmutabledictionary and then recalling them when a response comes back on a websocket. This turns async request into a block syntax. Here's the stripped down code:
- (void)sendMessage:(NSString*)message responseAction:(void (^)(id))responseAction
{
NSString *correlationID = (NSString*)[[message JSONValue] objectForKey:@"correlationId"];
[self.messageBlocks setObject:responseAction forKey:correlationID];
NSLog(@"Sending message: %@", correlationID);
[webSocket send:message];
}
- (void)webSocket:(SRWebSocket *)wsocket didReceiveMessage:(id)message;
{
NSString *correlationID = (NSString*)[[message JSONValue] objectForKey:@"correlationId"];
NSLog(@"Incoming message. CorrelationID: %@", correlationID);
void (^action)(id) = nil;
if (correlationID) {
action = [messageBlocks objectForKey:correlationID];
if (action) action([message JSONValue]);
[messageBlocks removeObjectForKey:correlationID];
}
}
注意:服务器以发送的correlationID与请求。因此每个响应通过该id链接到每个请求。
Note: The server responds with a correlationID that is sent with the request. So each response is linked to each request through that id.
这完美的,比我预想的更好。我有的问题是,这种方式运行块是安全的吗?正在调用[messageBlocks removeObjectForKey:correlationID];足以从内存中删除它。我记得pre-ARC,block_release是一个选项。
This works perfectly, better than I expected. The question I have is that is it safe to run blocks this way? Is calling [messageBlocks removeObjectForKey:correlationID]; enough to remove it from the memory. I remember pre-ARC, block_release was an option.
推荐答案
您需要复制基于堆栈的块才能将它们安全地存储在容器中。
You need to copy stack-based blocks in order to safely store them in a container.
[self.messageBlocks setObject:[responseAction copy] forKey:correlationID];
对于非ARC代码,您需要 -autorelease
it。
For non-ARC code, you need to -autorelease
it also.
[self.messageBlocks setObject:[[responseAction copy] autorelease] forKey:correlationID];
希望有帮助。
这篇关于在nsdictionary中的块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!