iOS Application Project与OS X Application Project对于plist使用的区别

  前几天因为在开源中国看到一个求源代码的问题:

模拟一个动物园系统MyZoo 

1、动物园里面有三种动物:Panda,Elephant,Kangaroo 
2、三种动物都有一定的数量(不止一只) 
3、动物有各自不同的食量(以天为单位的食量),并且每天都在消耗食物。 
4、动物园里的食物有固定的储备,而且假设三种动物都吃这一种食物。 
5、每个动物都有不同的生产周期,每当到了这种动物的生产周期,动物园就会出现一位新生宝宝(假设其食量和成年动物是一样的)。 
6、在主循环里模拟动物园的运转情况,要求在控制台上输出如下内容:第几天、动物的数量、动物园饲料的余量,直到饲料不够吃为止。 
7、动物的数量,食量,生产周期,饲料总量都应该是可以配置的(在同一个文件中统一配置) 

   因此创建了一个OS X Project:

  使用plist当做这个动物园系统的初始数据的配置,代码结构如下:

  在main.m文件中实现上述题目的要求:

#import <Foundation/Foundation.h>
#import "Tool.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        Panda *panda = [[Panda alloc] init];
        Elephant *elephant = [[Elephant alloc] init];
        Kangaroo *kangaroo = [[Kangaroo alloc] init];
        
        //读取plist
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
        NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
        NSLog(@"%@", plistPath);
        
        [Tool initWithAnimalDictionary:panda andDict:data];
        [Tool initWithAnimalDictionary:elephant andDict:data];
        [Tool initWithAnimalDictionary:kangaroo andDict:data];
        
        int fooder_num = 0;
        int surplus = 0;
        int day = 1;
        
        NSDictionary *fooderDict = [data objectForKey:@"fodder"];
        fooder_num = [[fooderDict objectForKey:@"count_num"] intValue];
        surplus = fooder_num;
        
        while(surplus > 0){
            if(0 == (day % [panda parturitionDays])){
                [panda setCount:([panda count] + 1)];
            }
            if(0 == (day % [elephant parturitionDays])){
                [elephant setCount:([elephant count] + 1)];
            }
            if(0 == (day % [kangaroo parturitionDays])){
                [kangaroo setCount:([kangaroo count] + 1)];
            }
            surplus = fooder_num - ([panda count] * [panda foodConsumption] + [elephant count] * [elephant foodConsumption] + [kangaroo count] * [kangaroo foodConsumption]);
            fooder_num = surplus;
            
            if(surplus){
                NSLog(@"第 %d 天,熊猫:%d 只,大象:%d 头,袋鼠:%d 只,饲料余量:%d 。
", day, [panda count], [elephant count], [kangaroo count], surplus);
            }
            day++;
        }
    }
    return 0;
}

   而这个时候遇见了问题,下面这句代码:

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];

   在执行时一直是null,无法找到文件路径.而后在iOS Application Project

中,plistPath是正确值,这下就不知道问题是什么了.看了[NSBundle mainBundle]中对于不同文件夹使用不同的方法,确定将文件放在工程下是使用上述代码.最后尝试各种方法,找到了一种解决方案:

  如上图所示,在Build Phase中Compile Sources中添加data.plist文件即可.

  不过,虽然解决了,可是根本原因却没有想明白,现在拿出来,希望大神们不吝赐教,谢谢.

  需要源代码的可以在评论留下邮箱,欢迎指正.

原文地址:https://www.cnblogs.com/chars/p/5004657.html