如何在 iOS 中从 .plist 添加和获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3921902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:53:47  来源:igfitidea点击:

How to add and get the values from .plist in iOS

iosobjective-cios4plist

提问by sekhar

I am implementing a application based on web services. In that I need to add a string as property in .plist and I need to get the value from the .plist whenever I need in the code.

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

回答by jv42

Here is a code sample:

这是一个代码示例:

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

回答by Nikhil Dinesh

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

回答by VSN

NSURL *url = [[NSBundle mainBundle] URLForResource:@"YOURPLIST" withExtension:@"plist"];
NSArray *playDictionariesArray = [[NSArray alloc ] initWithContentsOfURL:url];

NSLog(@"Here is the Dict %@",playDictionariesArray);

or you can use following also

或者你也可以使用以下

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Sample.plist"];

回答by kimimaro

Get from plist is very simple.

从 plist 获取非常简单。

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

If you want to add something to a plist, maybe you can find the answer here: How to write data in plist?

如果你想在 plist 中添加一些东西,也许你可以在这里找到答案: 如何在 plist 中写入数据?

But if you only want save some message in you app, NSUserDefaults is the better way.

但是如果你只想在你的应用程序中保存一些消息,NSUserDefaults 是更好的方法。

回答by Janosch Hübner

You can not do this. Any Bundle wether it is iOS or Mac OS is readonly, you can only read to it and you can't create files, write or do anything with the files in a bundle. This is part of the Security features of apple. You can use the NSDocumentsDirectory to writr and read your stuff you need for your app

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