尝试从plist读取整数会导致意外结果

时间:2013-12-01 02:59:39

标签: ios objective-c arrays plist

    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
    NSString *documentsDirectory = [paths objectAtIndex:0]; //2
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"levels.plist"]; //3

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath: path]) //4
    {
        NSString *bundle = [[NSBundle mainBundle] pathForResource:@"levels" ofType:@"plist"]; //5

        [fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
    }

    NSMutableDictionary *levels = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
    NSMutableArray *playLevel = (NSMutableArray *)[levels objectForKey: @"0"];


    // Initialize the correct grid for answer checking.
    correctGrid = [[NSMutableArray alloc] init];
    for (int row = 0; row < 5; row++) {
        NSMutableArray* subArr = [[NSMutableArray alloc] init];
        for (int col = 0; col < 5; col++) {
            int index = row * 5 + col;
            int number = [playLevel objectAtIndex:index];
            NSNumber *item = [NSNumber numberWithInt: number];
            [subArr addObject:item];
        }
        [correctGrid addObject: subArr];
    }

我是objective-c的新手,我正在尝试从结构化为数组字典的plist中读取整数值。在xcode中使用断点/调试器表明plist正在被成功读取。但是当我尝试从数组playLevel中检索数字时,每个数字都是一些可笑的高整数,例如164911184,当数组只是全零时。这与指针有关吗?帮助赞赏。

1 个答案:

答案 0 :(得分:1)

plist不能存储整数,它存储NSNumbers。所以,最有可能的是,你可以改变这两行,

int number = [playLevel objectAtIndex:index];
NSNumber *item = [NSNumber numberWithInt: number];

要,

NSNumber *item = [playLevel objectAtIndex:index];