在NSMutableData中加载层次结构

时间:2012-04-04 08:48:57

标签: iphone objective-c xcode

NSMutableData中是否有层次结构系统?如果是这样,我如何以层次结构方式加载信息? 实施例

//Create path to saving location
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSMutableData *gameData;
NSKeyedUnarchiver *decoder;
NSString *documentPath = [documentsDirectory stringByAppendingPathComponent:@"tierSave.dat"];
gameData = [NSData dataWithContentsOfFile:documentPath];
//end

//start loading
    for(NSArray* firstData in gameData){

    decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:gameData];

    int level1 = [decoder decodeIntegerForKey:level1];
    }
//end

然而在for(游戏数据中的NSArray * firstData)中,编译器告诉我gameData不会响应count,因为它是NSMutableData而不是NSMutableArray等,我如何完全重新实现上面的代码?

1 个答案:

答案 0 :(得分:1)

保存:

  • 使用您的多个NSData创建NSArray
  • 使用NSKeyedArchiver从NSArray制作NSData

装载:

  • 从文件
  • 加载NSData
  • 使用NSKeyedUnarchiver提取NSArray
  • 循环你的NSArray

在代码中:     NSData * data0 = [NSData数据]; //数据1     NSData * data1 = [NSData数据]; //数据2

/////////// SAVE
// now make a array
NSArray *array = [NSArray arrayWithObjects:data0, data1, nil];

// now archive the data
NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject:array];
// archivedData contains now a binary plist with your archived array including your NSData objects

[archivedData writeToFile:path atomically:YES];



/////// LOAD
NSData *archivedDataFromFile = [NSData dataWithContentsOfFile:path];

NSArray *newArray = [NSKeyedUnarchiver unarchiveObjectWithData:archivedDataFromFile];

NSData *dataLoaded0 = [newArray objectAtIndex:0];