0

这个问题很简单,我只是不知道如何处理它。

我通过以下方式读取数据:

[asyncSocket readDataWithTimeout:-1 tag:2];

NSString *failure = [serverJSONResponseParsed objectForKey:@"failure"];
NSLog(@"Contents of string failure: %@", failure);

if ([failure isEqualToString:@"none"]) {
    NSLog(@"Success Sending String");
    return TRUE;
}
else {
    NSLog(@"Failure: %@",failure);
    return FALSE;
}

现在,正如预期的那样,我的委托方法被调用并正确读取 JSON 数据:

-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    NSError *error;
    NSLog(@"didReadData: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    serverJSONResponseParsed = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    NSLog(@"didReadData test after dict: %@", [serverJSONResponseParsed objectForKey:@"failure"]);
}

问题是,由于 GCDAsyncSocket 是异步的,这段代码

NSString *failure = [serverJSONResponseParsed objectForKey:@"failure"];
NSLog(@"Contents of string failure: %@", failure);

if ([failure isEqualToString:@"none"]) {
    NSLog(@"Success Sending String");
    return TRUE;
}
else {
    NSLog(@"Failure: %@",failure);
    return FALSE;
}

[asyncSocket readDataWithTimeout:-1 tag:2];

在数据有机会被读取之前调用。我将如何确保读取数据,然后对其进行分析。

4

1 回答 1

1

该代码块需要在 didReadData 回调方法中,如下所示:

    -(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
        NSError *error;
        NSLog(@"didReadData: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        serverJSONResponseParsed = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        NSLog(@"didReadData test after dict: %@", [serverJSONResponseParsed objectForKey:@"failure"]);

    NSString *failure = [serverJSONResponseParsed objectForKey:@"failure"];
    NSLog(@"Contents of string failure: %@", failure);

    if ([failure isEqualToString:@"none"]) {
        NSLog(@"Success Sending String");
        return TRUE;
    }
    else {
        NSLog(@"Failure: %@",failure);
        return FALSE;
    }
}
于 2012-08-19T01:17:28.973 回答