0

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

4

3 回答 3

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];
于 2012-06-16T16:09:16.417 回答
0

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

于 2012-06-16T20:49:50.767 回答
0

对您的问题的简短回答是您不能将索引集保存到 plist 或用户默认值。有一个非常简短的对象类型列表,您可以将它们写入 plist。在 Xcode 中查找 NSDictionary 类的文档,并搜索字符串“property list object”,这就是他们告诉您哪些对象可以写入正确列表的地方。对象类型是 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];

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

于 2012-06-17T01:26:28.783 回答