在iPhone中保存会话数据 [英] Save Session Data in iPhone

查看:96
本文介绍了在iPhone中保存会话数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用中的不同位置存储数据,该应用可以访问应用中的对象。类似于php或全局变量中的会话。我知道我可以使用NSUserDefaults,但我不确定如何继续为它添加值然后访问它。例如,首先我要存储登录时使用的用户名,然后在第3屏幕上,我想保存他从公司列表中选择的用户的公司。然后在第5个屏幕上,我想保存用户选择的位置。然后我有不同的功能,用户可以根据他的选择使用。由于我是新手,我很抱歉,如果这是一个愚蠢的问题,但任何人都可以帮助我如何存储和检索可在整个应用程序中访问的多个数据。

I want to store data at different points in my app, that is accessible to objects across the app. Something similar to session in php or global variables. I know I can use NSUserDefaults but i am not sure how i would keep on adding values to it and then accessing it. Example, first i want to store the Username that is used during login, then on 3rd screen, i want to save the Company of that user that he selects from a list of companies. Then on the 5th screen i want to save the location that the user selects. And then I have different functionalities that the user can use depending on his selections. As I am a newbie i am sorry if this is a dumb question but can anybody help me as to how i would store and retrieve mulitple data that is accessible throughout the app.

推荐答案

您在评论中告诉我在属性列表中提供代码段。当然。没问题。您需要做的第一件事是创建属性列表文件。只需将属性列表类型的文件添加到项目中即可。我们称之为DataPoints.plist。出于此示例的目的,该文件将包含NSString类型的键值条目。在代码示例中,我只是提取属性列表条目并加载数组。现在,您可以使用数组执行任何操作。用它来加载表视图或其他任何东西。希望这可以帮助。如果有,请将其标记为已接受的答案。谢谢!

You asked me in your comment to provide a code snippet on property lists. Sure. No prob. First thing you need to do is create your property list file. Just add a file of type property list to your project. Let's call it DataPoints.plist. For purposes of this example, the file will contain key-value entries of type NSString. In the code example, I'm simply extracting the property list entries and loading up an array. Now you can do whatever you want with the array. Use it to load up a table view or whatever. Hope this helps. If it did, can you please mark it as the accepted answer. Thanks!

NSString *errorDesc;
NSPropertyListFormat format;
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"DataPoints" ofType:@"plist"];

NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];

NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization
                                     propertyListFromData:plistXML
                             mutabilityOption:NSPropertyListMutableContainersAndLeaves
                             format:&format
                             errorDescription:&errorDesc];

if (!temp) {
     // Handle Error
     Log(@"Error reading plist: %@, format: %d", errorDesc, format);
}

NSArray *dataPoints = [NSArray arrayWithArray:[temp objectForKey:@"DataPoints"]];

这篇关于在iPhone中保存会话数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆