2010-10-13 51 views
18

我正在实现基于Web服务的应用程序。因为我需要在.plist中添加一个字符串作为属性,并且我需要从代码中获取.plist中的值。你们能帮我解决吗?如何添加并从iPhone中的.plist中获取值sdk

+0

可能的重复[从plist获取数据到NSMutableArray并将NSMutableArray写入同一个plist iPhone](http://stackoverflow.com/questions/9193363/getting-data-from-plist-to-nsmutablearray-and-writing-the-nsmutablearray-to-same) – Monolo 2012-07-15 10:22:44

+0

请参阅[此链接](http://www.iphoneexamples.com/)。希望这会对你非常有帮助为你。祝一切顺利。 – Warrior 2010-10-13 12:54:45

回答

29

下面是一个代码示例:

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

嗨我得到了路径null你能帮我吗 – sekhar 2010-10-13 17:30:45

+0

你的plist文件必须添加到项目中,然后你必须在上面的代码中设置它的确切名称(包括大小写)。 – jv42 2010-10-14 08:51:27

+0

那么多层次的plists如何呢? http://i.imgur.com/bWNM3Va.png – 2015-04-20 16:18:56

15
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]; 
5
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中,也许你可以在这里找到答案: How to write data in plist?

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

0

你不能这样做。无论是iOS还是Mac OS,任何Bundle都是只读的,只能读取它,并且不能创建文件,编写文件或对文件进行任何操作。这是苹果的安全功能的一部分。你可以使用NSDocumentsDirectory来为你的应用程序编写并阅读你需要的东西

相关问题