[英]How can I save user preferences for my iPhone application?
I am building one Application and need to enter the access credentials (Org code, accesscode) before opening the application. 我正在构建一个应用程序,需要在打开应用程序之前输入访问凭据(组织代码,访问代码)。 when the user enter the access permissions for the first time then we need to save the preferences. 当用户首次输入访问权限时,我们需要保存首选项。 When the user open the app again, automatically he need to continue with application but not with access credentials. 当用户再次打开该应用程序时,他需要自动继续该应用程序,但不需要访问凭证。
And I build the code here 我在这里构建代码
There are no errors in log cat but preferences are not saving. 日志目录中没有错误,但首选项未保存。 I need to save the preferences and load when the application opens by the user. 我需要保存首选项并在用户打开应用程序时加载。 Am I doing anything wrong in the code? 我在代码中做错了吗?
This common function is to add your data to NSUserDefaults.. Look this is Class functions so You have to call this using your class name.. Write this in your AppDelegate implementation file.. 这个常见的功能是将数据添加到NSUserDefaults。.看起来这是Class函数,因此您必须使用您的类名来调用它。.在AppDelegate实现文件中编写它。
+(void)addToNSUserDefaults:(id)pObject forKey:(NSString*)pForKey
{
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setObject:pObject forKey:pForKey];
[defaults synchronize];
}
This is to get data from NSUserDefaults.. 这是从NSUserDefaults获取数据。
+(id)getFromNSUserDefaults:(NSString*)pForKey
{
id pReturnObject;
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
pReturnObject = [defaults valueForKey:pForKey];
return pReturnObject;
}
When you start application, Just Check this in this method of AppDelegate, 启动应用程序时,只需在AppDelegate的此方法中进行检查,
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSString *strtmp = [AppDelegate getFromNSUserDefaults:YOUR_KEY];
if(strtmp == nil)
{
//User have to enter data to save in User Defaults
}
else
{
//Application Starts without entering Code, as you have it in your UserDefaults
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.