国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > iOS > 正文

iOS子線程更新UI到主線程的三種方法

2019-11-09 15:22:11
字體:
來源:轉載
供稿:網友

以下代碼有什么問題?如何修復?

@interface TTWaitController : UIViewController@PRoperty (strong, nonatomic) UILabel *alert;@end@implementation TTWaitController- (void)viewDidLoad{ CGRect frame = CGRectMake(20, 200, 200, 20); self.alert = [[UILabel alloc] initWithFrame:frame]; self.alert.text = @"Please wait 10 seconds..."; self.alert.textColor = [UIColor whiteColor]; [self.view addSubview:self.alert]; NSOperationQueue *waitQueue = [[NSOperationQueue alloc] init]; [waitQueue addOperationWithBlock:^{ [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:10]]; self.alert.text = @"Thanks!"; }];}@end@implementation TTAppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window.rootViewController = [[TTWaitController alloc] init]; [self.window makeKeyAndVisible]; return YES;}

這段代碼是想提醒用戶等待10s,10s后在標簽上顯示“Thanks”,但多線程代碼部分NSOperationQueue的addOperationWithBlock函數不能保證block里面的語句是在主線程中運行的,UILabel顯示文字屬于UI更新,必須要在主線程進行,否則會有未知的操作,無法在界面上及時正常顯示。

解決方法是將UI更新的代碼寫在主線程上即可,代碼同步到主線程上主要有三種方法:NSThread、NSOperationQueue和GCD,三個層次的多線程都可以獲取主線程并同步。

NSThread級主線程同步:performSelectorOnMainThread

NSOperationQueue *waitQueue = [[NSOperationQueue alloc] init];[waitQueue addOperationWithBlock:^{ [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:10]]; // 同步到主線程 [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO];}];/** * UI更新函數 */- (void)updateUI { self.alert.text = @"Thanks!";}

NSOperationQueue級主線程同步:[NSOperationQueue mainQueue]

NSOperationQueue *waitQueue = [[NSOperationQueue alloc] init];[waitQueue addOperationWithBlock:^{ [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:10]]; // 同步到主線程 [[NSOperationQueue mainQueue] addOperationWithBlock:^{ self.alert.text = @"Thanks!"; }];}];

GCD級主線程同步:dispatch_get_main_queue

NSOperationQueue *waitQueue = [[NSOperationQueue alloc] init];[waitQueue addOperationWithBlock:^{ [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:3]]; // 同步到主線程 dispatch_async(dispatch_get_main_queue(), ^{ self.alert.text = @"Thanks!"; });}];
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 乳山市| 获嘉县| 大同县| 江源县| 偃师市| 正镶白旗| 增城市| 临汾市| 十堰市| 江川县| 息烽县| 巩留县| 杭锦旗| 偃师市| 弥渡县| 大新县| 新乐市| 洛浦县| 景泰县| 平安县| 南宁市| 大安市| 永城市| 凉城县| 金门县| 景洪市| 固安县| 诏安县| 呼伦贝尔市| 常州市| 浙江省| 苏尼特右旗| 井陉县| 临潭县| 西宁市| 阿尔山市| 平潭县| 柳州市| 瓮安县| 辛集市| 长治市|