我正在实现一个基于Web服务的应用程序。在这个应用程序中,我需要将一个字符串作为属性添加到.plist文件中,并且每当我在代码中需要时,我需要从.plist文件中获取该值。
我正在实现一个基于Web服务的应用程序。在这个应用程序中,我需要将一个字符串作为属性添加到.plist文件中,并且每当我在代码中需要时,我需要从.plist文件中获取该值。
以下是一个代码示例:
NSString *path = [[NSBundle mainBundle] pathForResource: @"YourPLIST" ofType: @"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile: path];
id obj = [dict objectForKey: @"YourKey"];
NSDictionary
,可以像任何其他字典一样使用它。 - jv42NSBundle* mainBundle = [NSBundle mainBundle];
// Reads the value of the custom key I added to the Info.plist
NSString *value = [mainBundle objectForInfoDictionaryKey:@"key"];
//Log the value
NSLog(@"Value = %@", value);
// Get the value for the "Bundle version" from the Info.plist
[mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"];
// Get the bundle identifier
[mainBundle bundleIdentifier];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"YOURPLIST" withExtension:@"plist"];
NSArray *playDictionariesArray = [[NSArray alloc ] initWithContentsOfURL:url];
NSLog(@"Here is the Dict %@",playDictionariesArray);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Sample.plist"];
从plist获取信息非常简单。
NSString *path = [[NSBundle mainBundle] pathForResource:@"SaveTags" ofType:@"plist"];
if (path) {
NSDictionary *root = [NSDictionary dictionaryWithContentsOfFile:path];
}
您不能这样做。无论是iOS还是Mac OS的Bundle都是只读的,您只能读取它,不能创建文件、写入或对Bundle中的文件进行任何操作。这是苹果安全功能的一部分。您可以使用NSDocumentsDirectory来编写和读取您的应用程序所需的内容。
我知道这个问题是在12年前提出的。但这是通过谷歌搜索出现的第一个SO问题。为了节省大家的时间,以下是如何在Swift中实现:
struct Config {
// option 1
static var apiRootURL: String {
guard let value = (Bundle.main.object(forInfoDictionaryKey: "BASE_URL") as? String), !value.isEmpty else {
fatalError("Base URL not found in PLIST")
}
return value
}
// option 2
static var databaseName: String {
guard let value = (Bundle.main.infoDictionary?["DB_NAME"] as? String), !value.isEmpty else {
fatalError("DB NAME not found in PLIST")
}
return value
}
}
注意这两个函数使用略有不同的方法来访问plist。但实际上它们几乎是相同的。
理论上可能没有plist。因此infoDictionary是可选的。但在这种情况下,第一种方法也会返回意外的值,导致错误。
苹果指出的一个实际区别是:
参考Bundle.main.object(forInfoDictionaryKey: "BASE_URL")
使用此方法优于其他访问方法,因为当本地化值可用时,它返回键的本地化值。