我想在带有object的新线程中传递一个(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
那么我怎么能通过后台线程接收param更改呢? 我知道c#有 ref 关键字来执行此操作。
在objective-c中我知道我可以将指针的地址传递给方法可以解决这个问题,但是传递参数的线程需要是 id 类型,我无法通过该方法的参数地址。那我该怎么办?
答案 0 :(得分:0)
在另一个帖子中,它不适用于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);
}
注意我说这是最简单的解决方案,它远非最佳解决方案。首先,您应该使用调度队列而不是启动新线程,而不是与调用者共享数据,您应该使用回调块将其传回。