iPhone应用程序保存状态 - nsmutableindexset和nsuintegers?

时间:2012-06-16 15:16:35

标签: objective-c ios cocoa-touch savestate

我是Xcode开发的新手,我正在尝试保存我的应用程序的状态,该状态跟踪多个索引集,整数和字符串。我已经尝试了很多不同的代码,并且无法将其保存到.plist中。保存以下数据类型NSMutableIndexSetsNSUIntegers的最佳方法是什么?任何方向都会很棒,谢谢。

3 个答案:

答案 0 :(得分:0)

使用以下代码

//Saving
NSMutableIndexSet *set = [[NSMutableIndexSet alloc] init];

[set addIndex:1];
[set addIndex:2];

NSMutableArray *arrToSave = [[NSMutableArray alloc] init];

NSUInteger currentIndex = [set firstIndex];
while (currentIndex != NSNotFound)
{
    [arrToSave addObject:[NSNumber numberWithInt:currentIndex]];
    currentIndex = [set indexGreaterThanIndex:currentIndex];
}

NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
NSUInteger integer = 100;
NSString *savePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/savePath.txt"];

[dic setValue:arrToSave forKey:@"set"];
[dic setValue:[NSNumber numberWithUnsignedInt:integer] forKey:@"int"];
[dic writeToFile:savePath atomically:YES];



//Loading
NSString *savePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/savePath.txt"];
NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithContentsOfFile:savePath];

NSArray *arr = [dic valueForKey:@"set"];
NSMutableIndexSet *set = [[NSMutableIndexSet alloc] init];
[set addIndex:[[arr objectAtIndex:0] unsignedIntValue]];
[set addIndex:[[arr objectAtIndex:1] unsignedIntValue]];
NSUInteger integer = [[dic valueForKey:@"int"] unsignedIntValue];

答案 1 :(得分:0)

据我所知,您可以将一组项目存档到plist文件中。 从内存(这意味着你应该在文档中查找)它是NSString,NSArray,NSDictionary,NSData,NSNumber和......其他几个我不记得了。关键是您的索引集可能不是其中之一,因此您需要将其转换为其他内容,将其归档并在唤醒时取消归档并重新转换回来。

答案 2 :(得分:0)

您的问题的简短回答是您无法将索引集保存为plist或用户默认值。您可以将一个非常短的对象类型列表写入plist。在Xcode中查找NSDictionary类上的文档,并搜索字符串“属性列表对象”,这是他们告诉您哪些对象可以写入正确列表的位置。对象类型是NSString,NSData,NSDate,NSNumber,NSArray或NSDictionary对象。

Omar Abdelhafith发布了一个非常长而复杂的代码块,用于将索引集转换为数组,这应该可行。

然而,有一种更简单的方法。 NSIndexSet符合NSCoding协议,这意味着您可以通过一次调用将其转换为NSData:

NSData *setData = [NSKeyedArchiver archivedDataWithRootObject: mySet];

然后将其转回索引集:

NSIndexSet *setFromData= [NSKeyedUnarchiver unarchiveObjectWithData: setData];
NSMutableIndexSet *mutableSet = [setFromData mutableCopy];

请注意,对于所有这些方法,如果你从一个可变对象(set,array,dictionary等)开始,那么当你读回它时,你得到的对象将是一个不可变的版本。您必须手动将其转换为可变版本。大多数具有可变变体的对象都支持mutableCopy方法。