我是iOS开发人员的新手。 我一直试图找到答案,但没有明确的解决方案..
我有一个名为FirstView.m的视图
还有AppDelegate.m
后台任务在AppDelegate.m中运行,它根据最接近手机的信标更新名为“text”的变量。
当应用程序在FirstView中时,我想根据AppDelegate的变量文本更新FirstView内的UILabel。
我知道这可以通过在FirstView中运行后台线程来完成,每1秒检查一次AppDelegate中的变量是否被更改,但这对我来说似乎没有效率,没有必要为此运行两个后台线程同样的任务。
我的问题是,有没有办法从AppDelegate本身更新标签? performSelectorOnMainThread上有什么东西?
谢谢!
I am fairly new to iOS dev. I have been trying to find an answer to this but don't have a definite solution..
I have a view called FirstView.m
And there's AppDelegate.m
A background task is running in AppDelegate.m which updates a variable called `text' depending upon the closest beacon to the phone.
When the app is in FirstView, I want to update a UILabel inside FirstView as per the variable text of AppDelegate.
I know this can be done by running a background thread in FirstView which every 1 second checks whether the variable in AppDelegate was changed or not, but this doesn't seem efficient to me at all, there is no point running two background threads for the same task.
My questions is, is there a way to update the label from AppDelegate itself ? Something on the lines of performSelectorOnMainThread ?
Thanks!
最满意答案
只要值发生变化,您就可以在AppDelegate的userInfo字典中发布带有文本的通知:
text = [iBeacon updateText]; // just a random method name I made up [[NSNotificationCenter defaultCenter] postNotificationName:@"textChanged" object:self userInfo:@{@"text":text}];然后在FirstView中,您可以侦听该通知以更新UI(通常在viewDidLoad或viewDidAppear: )。 确保在ViewView中取消分配视图控制器之前取消注册,以便没有内存泄漏。 注册和更新UI的示例
你可以这样注册:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextChanged:) name:@"textChanged" object:nil];然后更新UI:
- (void)handleTextChanged:(NSNotification *)notification { // Be sure to update the UI on the main thread dispatch_async(dispatch_get_main_queue(), ^{ self.label.text = notification.userInfo[@"text"]; }); }最后,取消注册通知:
[[NSNotificationCenter defaultCenter] removeObserver:self];You could post a notification with the text in the userInfo dictionary in the AppDelegate anytime that value changes:
text = [iBeacon updateText]; // just a random method name I made up [[NSNotificationCenter defaultCenter] postNotificationName:@"textChanged" object:self userInfo:@{@"text":text}];Then in the FirstView you can listen for that notification to update the UI (normally in viewDidLoad or in viewDidAppear:). Be sure to unregister before the view controller is dealloced somewhere in FirstView so there are no memory leaks. Example for registering and updating UI
You can register like this:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextChanged:) name:@"textChanged" object:nil];Then update the UI:
- (void)handleTextChanged:(NSNotification *)notification { // Be sure to update the UI on the main thread dispatch_async(dispatch_get_main_queue(), ^{ self.label.text = notification.userInfo[@"text"]; }); }And finally, unregister for notifications:
[[NSNotificationCenter defaultCenter] removeObserver:self];更多推荐
发布评论