2016-08-22 94 views
0

我有3個名爲level0,level1,level2的plist文件,所有這個plist都有相同的結構,它由數字變量和數組組成。我用這個plist的數據啓動我的應用程序。來自plist的字典

+(instancetype)levelWithNum:(int)levelNum; { 
    NSString* fileName = [NSString stringWithFormat:@"level%i.plist", levelNum]; 
    NSString* levelPath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:fileName]; 
    NSDictionary *levelDic = [NSDictionary dictionaryWithContentsOfFile:levelPath]; 
    NSAssert(levelDic, @"level no loaded"); 
    Level *l = [[Level alloc]init]; 
    l.coinsPerLvl = [levelDic[@"coinsPerLvl"] integerValue]; 
    l.words = levelDic[@"words"]; 
    return l; 
} 

現在我決定只使用一個plist並添加它3字典。我如何才能從plist中讀取一個字典,就像上面的示例中我使用plist文件一樣。

坦克的任何幫助!

enter image description here

+0

是什麼在levels.plist問題? –

回答

1

你只需要一箇中間變量多數民衆贊成代表根字典和提取根字典級字典,e.g:

+(instancetype)levelWithNum:(int)levelNum; { 

    NSString  *levelsPlist = [[NSBundle mainBundle] pathForResource:@"levels" ofType:@"plist"]; 
    NSDictionary *rootDict  = [NSDictionary dictionaryWithContentsOfFile: levelsPlist]; 
    NSString  *levelKey  = [NSString stringWithFormat:@"level%i", levelNum]; 

    NSDictionary *levelDic = rootDict[levelKey]; 

    NSAssert(levelDic, @"level no loaded"); 

    Level *l = [[Level alloc]init]; 
    l.coinsPerLvl = [levelDic[@"coinsPerLvl"] integerValue]; 
    l.words = levelDic[@"words"]; 
    return l; 
} 

希望它能幫助。

+0

謝謝!它幫助我很多! –

0

讓你的plist root成爲一個數組(如下所示)。這樣你可以輕鬆獲得關卡信息。

示例代碼

+(void)levelWithNum:(int)levelNum { 

NSString* fileName = @"level.plist"; 
NSString* levelPath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:fileName]; 
NSArray *levelsArray = [NSArray arrayWithContentsOfFile:levelPath]; 
NSAssert(levelsArray, @"level no loaded"); 


Level *l = [[Level alloc]init]; 
l.coinsPerLvl = [[levelsArray objectAtIndex:levelNum][@"coinsPerLvl"] integerValue]; 
l.words = [[levelsArray objectAtIndex:levelNum][@"words"] integerValue]; 
return l; 
} 

sample plist screen shot