跨选项卡栏应用程序同步plist [英] Synchronizing plist across a Tab Bar Application
问题描述
我有一个包含三个选项卡的应用程序,该应用程序共享一个用于连接信息(客户端ID,服务器地址,端口号)的plist.在每个视图控制器中,都会在viewDidLoad方法中初始化一个NSUserDefaults对象:
I have a three tab application that shares a plist for connection information (Client ID, Server Address, Port Number). In each of the view controllers, an NSUserDefaults object is initialized within the viewDidLoad method:
- (void)viewDidLoad {
[super viewDidLoad];
// load default settings into class instance variables
defaults = [NSUserDefaults standardUserDefaults];
self.clientID = [defaults objectForKey:@"clientID"];
self.serverAddress = [defaults objectForKey:@"serverAddress"];
self.serverPort = [defaults objectForKey:@"serverPort"];
}
我的一个视图代表一个设置"页面,该页面允许用户更改plist.但是,更新plist时,更改不会反映在所有选项卡视图中,因为每个对象都需要同步:
One of my views represents a "Settings" page that allows a user to make changes to the plist. However, when the plist is updated, the changes aren't reflected across all of the tab views because a synchronize is needed for each of the objects:
[defaults synchronize];
我了解到viewDidLoad方法在应用程序的生命周期内仅被调用一次(至少对于Tab Bar应用程序而言),因此,我无法在此处放置同步调用.然后,我转到AppDelegate类,发现了tabBarController方法.如何使用此方法在所有视图控制器之间同步NSUserDefaults对象,而无需使用同步按钮?这是打开应用程序时共享/调整首选项的正确方法吗?
I've learned that the viewDidLoad method is only called once during the lifetime of an application (at least for a Tab Bar application), so, I can't put the synchronize calls here. I then turned to the AppDelegate class and discovered the tabBarController method. How do I use this method to synchronize the NSUserDefaults objects across all view controllers without the need for a sync button? Is this even the correct way of sharing/adjusting preferences while an application is open?
我现在在这里:
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
// I need to synchronize somewhere in here???
switch (tabBarController.selectedIndex)
{
case 0:
NSLog(@"Tab 0 selected");
break;
case 1:
NSLog(@"Tab 1 selected");
break;
case 2:
NSLog(@"Tab 2 Selected");
break;
}
}
提前谢谢.
推荐答案
尝试同步viewWillAppear
(而不是viewDidLoad
)中的默认值.
Try syncing the defaults in viewWillAppear
instead of viewDidLoad
.
例如,如果存在内存问题,可能会多次调用viewDidLoad
(在这种情况下,将在两次之间调用viewDidUnload
).
It may happen that viewDidLoad
is called multiple times (in which case, viewDidUnload
will have been called between), for example, if there is a memory issue.
通过同步viewWillAppear
中的默认值,可以确保相关的UIViewController
在成为选定的视图控制器之前得到更新.
By synchronizing the defaults in viewWillAppear
, you are ensuring that the relevant UIViewController
is updated just before it becomes the selected view controller.
这篇关于跨选项卡栏应用程序同步plist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!