因此,我将阻止操作存储到nsmutabledictionary中,然后在Websocket上返回响应时将其重新调用。这会将异步请求转换为块语法。这是精简的代码:
- (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链接到每个请求。
效果很好,比我预期的要好。我的问题是,以这种方式运行块是否安全?正在调用[messageBlocks removeObjectForKey:correlationID];足以将其从内存中删除。我记得在ARC之前,block_release是一个选项。
最佳答案
您需要复制基于堆栈的块,以便将它们安全地存储在容器中。
[self.messageBlocks setObject:[responseAction copy] forKey:correlationID];
对于非ARC代码,您还需要对其进行
-autorelease
编码。[self.messageBlocks setObject:[[responseAction copy] autorelease] forKey:correlationID];
希望能有所帮助。
关于ios - nsdictionary中的块?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12310374/