HomeViewController.h更改文本在後臺線程不工作
#import "DataParser.h"
@interface HomeViewController : UIViewController <DataParserDelegate>
{
UILabel *theLabel;
}
HomeViewController.m
#import "HomeViewController.h"
@implementation HomeViewController
-(void)viewDidLoad
{
theLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 200, 100, 30)];
theLabel.text = @"Bob";
theLabel.font = [UIFont italicSystemFontOfSize:20.0];
theLabel.textColor = [UIColor whiteColor];
theLabel.backgroundColor = [UIColor blueColor];
[self.view addSubview:theLabel];
UIButton *theButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[theButton addTarget:self action:@selector(clicked:) forControlEvents:UIControlEventTouchUpInside];
[theButton setTitle:@"Big Button" forState:UIControlStateNormal];
theButton.frame = CGRectMake(100,100,200,50);
[self.view addSubview:theButton];
}
-(void)clicked:(id)sender
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND,0),
^{
DataParser *data = [[DataParser alloc] init];
data.delegate = self;
[data loadSomething];
dispatch_async(dispatch_get_main_queue(),
^{
NSLog(@"Thread done");
});
});
}
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
theLabel.frame = CGRectMake(250,250,100,30);
theLabel.text = @"This message displays fine";
}
-(void)loadMessage:(NSString *)message
{
NSLog(@"Received message: %@", message);
theLabel.frame = CGRectMake(300,300,100,30);
theLabel.text = @"This message won't display";
}
@end
DataParser.h
@protocol DataParserDelegate;
@interface DataParser : NSObject
@property (weak, nonatomic) id <DataParserDelegate> delegate;
-(void)loadSomething;
@end
@protocol DataParserDelegate <NSObject>
-(void)loadMessage:(NSString *)message;
@end
DataParser.m
#import "DataParser.h"
@implementation DataParser
@synthesize delegate=_delegate;
-(void)loadSomething
{
[[self delegate] loadMessage:@"ASDF"];
}
@end
- = - = - = - = - = - = - = - = - = - = - = - = - = -
基本上,我創建了一個標籤,並將其添加到屏幕上。在這一點上,你可以清楚地看到一個白色文字的藍色按鈕,上面寫着「Bob」。當你旋轉屏幕時,按鈕改變文本和位置就好了。然而,如果我點擊按鈕,它會創建一個dataParser對象,將委託設置爲self,並調用「loadSomething」。在dataParser對象中,「loadSomething」僅調用委託方法「loadMessage」。
問題是,當調用「loadMessage」時,NSLog語句正確打印(「Received message:ASDF」),但是,標籤不會移動並且不會更改其文本。爲什麼是這樣?我該如何解決這個問題?
是他在主線程中調用的嗎? (UIKit不是線程安全的) – Ganzolo
@Ganzolo實際上,DataParser實際上是在後臺線程中運行的......我想我應該修改我的代碼以顯示它。這可能是問題嗎? – Highrule