我是Objective-C的新手。
首先请看代码:
这是属性:
@property (atomic) IBOutlet NSTextView *txtResponse;
这就是行动:
- (IBAction)sendReq:(id)sender {
@synchronized(self)
{
request *req = [[request alloc] init];
voidCallback callback = ^(NSURLResponse *resp, NSData *data, NSError *error) {
NSString *val = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[self.txtResponse setString:val];
//NSLog(val);
};
[req setUrl:[[NSURL alloc] initWithString:@"http://foo.bar"]];
[req setCallback:callback];
[req send];
}
}
当我尝试使用[self.txtResponse setString:val];
时,用户界面会冻结
我还尝试了没有@synchronized(self)
的代码
问题在哪里?
提前谢谢!
答案 0 :(得分:0)
第3天我正在使用objective-c并最终找到答案:)
我使用了performSelectorOnMainThread
并解决了问题
- (IBAction)sendReq:(id)sender {
request *req = [[request alloc] init];
voidCallback callback = ^(NSURLResponse *resp, NSData *data, NSError *error) {
NSString *val = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[self performSelectorOnMainThread:@selector(setResponseValue:) withObject:val waitUntilDone:NO];
};
[req setUrl:[[NSURL alloc] initWithString:@"http://programming.com"]];
[req setCallback:callback];
[req send];
}
- (void)setResponseValue:(NSString *)resp
{
[self.txtResponse setString:resp];
//NSLog(resp);
}