iOS - 从plist中提取数据不起作用

时间:2016-05-06 07:39:20

标签: ios objective-c plist

这是一项例行练习。我在我目前的项目中已经多次完成它并且它运行良好。我复制了代码行,用于行,相同的初始化。我的plist数据进入字典,但是在初始化时它不会进入各自的数组。我有一个名为initArraysPlist

的方法
-(void)initArraysPlist{
NSString *path1 = [[NSBundle mainBundle] pathForResource:@"trainerProfile" ofType:@"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict1 = [[NSDictionary alloc] initWithContentsOfFile:path1];

trainerNames = [dict1 objectForKey:@"Names"];
trainerIcons = [dict1 objectForKey:@"Icons"];
trainerFactSheet= [dict1 objectForKey:@"Fact Sheet"];
trainerFocus = [dict1 objectForKey:@"Focus"];
trainerContactInfo= [dict1 objectForKey:@"Contact Info"];

}

我已经完成了几次,它目前在我的代码中工作。所有的价值都是正确的。我多次检查过它。什么时候

2 个答案:

答案 0 :(得分:1)

请阅读每行的评论。

  NSString *path1 = [[NSBundle mainBundle] pathForResource:@"trainerProfile" ofType:@"plist"]; // **check if your plist is actually added in Bundle.If its there move to second line , if not then add plist in bundle.**

   NSDictionary *dict1 = [[NSDictionary alloc]    initWithContentsOfFile:path1];// **if plist is added in bundle , then check if you are getting value for dict1 . If no then you might be making some mistake in plist structure.** 

如需更多说明,请尽可能发布您的plist。

答案 1 :(得分:0)

请尝试使用此代码,这对您有帮助

// Read plist from bundle and get Root Dictionary out of it

NSDictionary *dictRoot = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]];

// Your dictionary contains an array of dictionary
// Now pull an Array out of it.

NSArray *arrayList = [NSArray arrayWithArray:[dictRoot objectForKey:@"catlist"]];

// Now a loop through Array to fetch single Item from catList which is Dictionary

[arrayList enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL *stop) {

    // Fetch Single Item
    // Here obj will return a dictionary

     NSLog(@"Category name : %@",[obj valueForKey:@"category_name"]);
     NSLog(@"Category id   : %@",[obj valueForKey:@"cid"]);
}];