How do I read a value of a property list file key into a string for iphone app using Xcode

老子叫甜甜 提交于 2019-12-08 10:40:13

问题


I have a property list file "someFile.plist" and within the plist I have two rows "row1" and "row2" each with a string value that is either "Y" or "N" - If I want to check the "someFile.plist" file for "row2" to obtain the value of that row and read it into a string in objective c, how would I do that? I am coding for an iphone App using Xcode.


回答1:


Load the .plist into a NSDictionary like:

NSString *path = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];

Loop through the NSDictionary using something like:

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}



回答2:


If you want to get the value of "row2" to String then it depends if you are having Dictionary type or Array type. In the case of Dictionary type:

NSString *path = [[NSBundle mainBundle] pathForResource:@"pListFileName" ofType:@"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSString valueOfRow2 = [dict objectForKey:@"row2"]);
NSLog(@"The value of row2 is %@", valueOfRow2);

and in the case of Array:

NSString *path = [[NSBundle mainBundle] pathForResource:@"pListFileName" ofType:@"plist"];
NSArray *array = [NSArray arrayWithContentsOfFile: path];
//the indexes of NSArray is counted from 0, not from 1
NSString valueOfRow2 = [array objectAtIndex:1];
NSLog(@"The value of row2 is %@", valueOfRow2);

You can use NSMutableDictionary and NSMutableArray respectively. It would be more easy to modify them.




回答3:


For Swift 3.0:

if let path = Bundle.main.path(forResource: "YourPlistFile", ofType: "plist"), let dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
            let value = dict["KeyInYourPlistFile"] as! String
    }


来源:https://stackoverflow.com/questions/12250739/how-do-i-read-a-value-of-a-property-list-file-key-into-a-string-for-iphone-app-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!