如何在带有object的新线程中传递NSString*参数



我想在带有对象的新线程中传递一个(NSString*)。这样我就可以在后台线程和主线程中更改它像这个的代码

//this method will create a thread for sleepAndAssign ,and i want to pass the param type is NSString * .  the background thread is to change the param's value. 
 NSString *param = @"0";
[self performSelectorInBackground:@selector(sleepAndAssign:) withObject:param];
NSLog(@"param = %@", param);
[NSThread sleepForTimeInterval:4];
NSLog(@"param = %@", param);
...
- (void)sleepAndAssign:(NSString *)param {
    [NSThread sleepForTimeInterval:1];
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:2];
    [NSThread sleepUntilDate:date];
    param = @"5";
    NSLog(@"backgroundthread param = %@", param);
}

结果输出为

param = 0
backgroundthread param = 5
param = 0

那么我该如何接收后台线程对参数的更改呢?我知道c#有ref关键字来做这件事。

在objective-c中,我知道我可以将指针的地址传递给方法可以解决这个问题,但传递param的线程需要是id类型,我不能将param的地址传递到方法。那我该怎么办呢?

在另一个线程中,它无法与ref一起工作。

最简单的解决方案是使用包装器对象:

@interface MyData : NSObject
@property (atomic, strong, readwrite) NSString *param;
@end
@implementation MyData
@end

MyData *data = [[MyData alloc] init];
data.param = @"0";
[self performSelectorInBackground:@selector(sleepAndAssign:) withObject:data];
NSLog(@"param = %@", data.param);
[NSThread sleepForTimeInterval:4];
NSLog(@"param = %@", data.param);
...
- (void)sleepAndAssign:(MyData *)data {
     [NSThread sleepForTimeInterval:1];
     NSDate *date = [NSDate dateWithTimeIntervalSinceNow:2];
     [NSThread sleepUntilDate:date];
     data.param = @"5";
     NSLog(@"backgroundthread param = %@", data.param);
}

注意,我说这是最简单的解决方案,但远不是最好的解决方案。首先,您应该使用一个调度队列,而不是启动新线程,也不应该与调用方共享数据,而是应该使用回调块将数据传回。

最新更新