无法将值传递给`Grand Central Dispatch`中的NSString

时间:2014-07-21 06:21:24

标签: ios grand-central-dispatch

__block NSMutableString *retCode;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    retCode = @"1";
    self.returnCode = retCode;
});

我使用此代码,但它将NULL值传递给returnCode;

3 个答案:

答案 0 :(得分:3)

您不必在首先给出的实例中使用NSMutableString(因为您要覆盖该值)。所以,您可以轻松地使用NSString(可能更好,除非您实际上打算在您的调度中附加/前置/操作该字符串)。

话虽这么说,你也应该考虑在进入你的区块之前对自己应用__weak引用。

__weak typeof( self ) weakSelf = self;

最后,returnCode实际上可能是NULL IF 您试图在主线程上访问它 - 它与DEFAULT优先级全局队列不在同一个线程上。我做这个注释是因为它取决于你试图访问你的self.returnCode时 - 因为如果你试图在之前看看它是不是nil 然后执行调度队列是 - 它将是nil / null。

尝试NSLog( @"Value of returnCode = %@", self.returnCode );,您应该会看到它实际上已被分配。

完整示例:

__block NSString *retCode;
__weak typeof( self ) weakSelf = self;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    retCode = @"1";
    weakSelf.returnCode = retCode;

    NSLog( @"Value of returnCode = %@", weakSelf.returnCode );
});

答案 1 :(得分:1)

您使用的是NSMutableString *retCode,因此您需要在@"1"中指定NSMutableString而不是NSString

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

  retCode=   [NSMutableString stringWithFormat:@"1"];
//use here or
self.returnCode = retCode;

});

答案 2 :(得分:1)

 __block NSMutableString *retCode=[[NSMutableString alloc]init];

AppDelegate* __weak weakSelf = self;


dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

[retCode appendString:@"1"];
    weakSelf.returnCode = retCode;
    NSLog(@"%@",weakSelf.returnCode);

});