在一个C#应用程序中,我通常使用app.config
文件来保存一些数据,以便在需要时加载应用程序(例如连接字符串)。
在iOS应用程序中保存这样的信息,最好的方法是什么?
在一个C#应用程序中,我通常使用app.config
文件来保存一些数据,以便在需要时加载应用程序(例如连接字符串)。
在iOS应用程序中保存这样的信息,最好的方法是什么?
使用NSBundle在应用程序中加载文件,例如
NSString *path = [[NSBundle mainBundle] pathForResource:@"settings" ofType:@"plist"];
NSDictionary *settings = [[NSDictionary alloc] initWithContentsOfFile:path];
你可以像使用普通字典一样访问你的键。只是不要忘记在结束时[释放]它。对于像连接字符串这样的小数据,我会使用NSUserDefaults。
当您想保存连接字符串时,可以执行以下操作:
[[NSUserDefaults standardUserDefaults] setObject:myConnectionString
forKey:@"connectionString"];
当您想要加载它时,您需要执行以下操作:
myConnectionString = [[NSUserDefaults standardUserDefaults]
stringForKey:@"connectionString"];
NSString *settingsPath = [@"~/pathtoconfig.plist" stringByExpandingTildeInPath];
NSMutableDictionary *settings = [NSMutableDictionary dictionary];
if([[NSFileManager defaultManager] fileExistsAtPath:settingsPath]){
settings = [NSMutableDictionary dictionaryWithContentsOfFile:settingsPath];
}
// writing settings
[settings writeToFile:settingsPath atomically:YES];
由于我不知道您对Objective-C的熟悉程度,因此我想指出:
使用iOS 8.3和Swift创建iOS应用程序配置文件:
let path: String = NSBundle.mainBundle().pathForResource("Info", ofType: "plist")!
let nsDictionaryInfoPlist: NSDictionary = NSDictionary(contentsOfFile: path)!
// Usage example: Google Maps iOS SDK/API Configuration.
GMSServices.provideAPIKey(nsDictionaryInfoPlist.objectForKey("GoogleMapsiOSAPIKey") as! String)
更新至Swift 3 Xcode 8
在项目中添加一个名为“Sample.plist”的新属性列表。然后查看以下示例。
let path: String = Bundle.main.path(forResource: "Sample", ofType: "plist")!
let sampleConf: NSDictionary = NSDictionary(contentsOfFile: path)!
print(sampleConf.object(forKey: "test") as! String)
我使用属性列表来存储小数据片段 - 在这里查看如何使用它们:
http://iphoneincubator.com/blog/tag/nspropertylistserialization