如何在iOS中添加和获取.plist文件中的值

22

我正在实现一个基于Web服务的应用程序。在这个应用程序中,我需要将一个字符串作为属性添加到.plist文件中,并且每当我在代码中需要时,我需要从.plist文件中获取该值。


6个回答

37

以下是一个代码示例:

NSString *path = [[NSBundle mainBundle] pathForResource: @"YourPLIST" ofType: @"plist"]; 
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile: path];
id obj = [dict objectForKey: @"YourKey"];

1
嗨,我得到了路径为空,你能帮我吗? - sekhar
你的plist文件必须被添加到项目中,然后你必须在代码中设置它的确切名称(包括大小写)。 - jv42
1
@BenC.R.Leggiero 一旦您执行了第二行,您就拥有了一个普通的NSDictionary,可以像任何其他字典一样使用它。 - jv42

21
NSBundle* 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];

6
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"];

2

从plist获取信息非常简单。

NSString *path = [[NSBundle mainBundle] pathForResource:@"SaveTags" ofType:@"plist"];
if (path) {
    NSDictionary *root = [NSDictionary dictionaryWithContentsOfFile:path];
}

如果您想向plist中添加内容,也许可以在这里找到答案:如何在plist中写入数据? 但是如果您只想在应用程序中保存一些消息,NSUserDefaults是更好的方法。

1

您不能这样做。无论是iOS还是Mac OS的Bundle都是只读的,您只能读取它,不能创建文件、写入或对Bundle中的文件进行任何操作。这是苹果安全功能的一部分。您可以使用NSDocumentsDirectory来编写和读取您的应用程序所需的内容。


0

Swift

我知道这个问题是在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")

使用此方法优于其他访问方法,因为当本地化值可用时,它返回键的本地化值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接