国产探花免费观看_亚洲丰满少妇自慰呻吟_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!"; });}];
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 镇原县| 马关县| 浮山县| 陕西省| 临夏县| 兴化市| 元江| 玛曲县| 海宁市| 陕西省| 兰州市| 阿克苏市| 桐庐县| 喀喇沁旗| 泰兴市| 奉贤区| 米泉市| 大同县| 聊城市| 肇源县| 红河县| 临邑县| 祁东县| 宁远县| 凤庆县| 东乡族自治县| 彰化县| 循化| 信阳市| 灵川县| 德兴市| 简阳市| 舟曲县| 安远县| 通许县| 吐鲁番市| 唐海县| 淮南市| 廊坊市| 明光市| 尚义县|