2012-06-16 26 views
0

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

回答

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方法。

+0

这工作,并减少了所需的代码。谢谢,邓肯。 – rossi

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]; 
+0

谢谢,这适用于一组,但如何更改代码以使用nsmutableindexset?这是我不知道如何转换的行,[dic setValue:[set allObjects] forKey:@“set”];?如果我将'set'更改为我的nsmutableindexset,我得到 – rossi

+0

我得到一个错误'Arc issue,nsmutableindexset'没有可见的@interface'声明选择器allObjects'。感谢奥马尔的帮助。有关将此行转换为索引集的任何想法? – rossi

+0

@rossi请检查更新的答案 –

0

据我所知有可以归档到plist文件中项目的设置列表。 从内存(这意味着你应该去查看它的文档)它是NSString,NSArray,NSDictionary,NSData,NSNumber和...我记不起来的其他几个。这一点是你的索引集可能不是其中之一,所以你需要将其转换为其他东西,将其归档并唤醒后将其解压缩并重新恢复。