2012-06-16 27 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和...我記不起來的其他幾個。這一點是你的索引集可能不是其中之一,所以你需要將其轉換爲其他東西,將其歸檔並喚醒後將其解壓縮並重新恢復。