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

首頁 > 系統 > iOS > 正文

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

2019-11-09 16:37:43
字體:
來源:轉載
供稿:網友

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

@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!"; });}];
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 综艺| 贺州市| 牟定县| 留坝县| 板桥市| 资兴市| 五华县| 阿拉尔市| 南平市| 平谷区| 延津县| 平阴县| 武义县| 古交市| 昂仁县| 滁州市| 镇远县| 临汾市| 林州市| 理塘县| 巴马| 翁牛特旗| 铁岭市| 左权县| 尉犁县| 耿马| 盐津县| 宁蒗| 蓝田县| 温宿县| 雅江县| 洛扎县| 乌鲁木齐县| 洱源县| 双鸭山市| 富宁县| 张家口市| 张家港市| 新蔡县| 兰溪市| 寿宁县|