私は Xcode 開発を始めたばかりで、複数のインデックス セット、整数、および文字列を追跡するアプリの状態を保存しようとしています。私は多くの異なるコードを試しましたが、.plist に保存して動作させることができませんでした。NSMutableIndexSets
次のデータ型を保存するための最良の方法は何 NSUIntegers
ですか? どんな方向でもいいです、ありがとう。
3 に答える
あなたの質問に対する簡単な答えは、インデックス セットを plist またはユーザーの既定値に保存できないということです。plist に書き込むことができるオブジェクト タイプの非常に短いリストがあります。Xcode の NSDictionary クラスのドキュメントを参照し、"property list object" という文字列を検索します。ここで、適切なリストに書き込むことができるオブジェクトが示されます。オブジェクト タイプは、NSString、NSData、NSDate、NSNumber、NSArray、または NSDictionary オブジェクトです。
Omar Abdelhafith は、インデックス セットを配列に変換するための非常に長く複雑なコード ブロックを投稿しました。
ただし、もっと簡単な方法があります。NSIndexSet は NSCoding プロトコルに準拠しています。つまり、1 回の呼び出しで NSData に変換できます。
NSData *setData = [NSKeyedArchiver archivedDataWithRootObject: mySet];
そしてそれをインデックスセットに戻すには:
NSIndexSet *setFromData= [NSKeyedUnarchiver unarchiveObjectWithData: setData];
NSMutableIndexSet *mutableSet = [setFromData mutableCopy];
これらすべてのアプローチで、変更可能なオブジェクト (セット、配列、辞書など) から開始すると、それを読み返すと、返されるオブジェクトは不変のバージョンになることに注意してください。変更可能なバージョンに手動で変換する必要があります。変更可能なバリアントを持つほとんどのオブジェクトは、メソッド mutableCopy をサポートしています。
私が知る限り、plist ファイルにアーカイブできるアイテムのセット リストがあります。メモリから(つまり、ドキュメントで調べる必要があります)、NSString、NSArray、NSDictionary、NSData、NSNumber、および...覚えていない他のいくつかです。ポイントは、あなたのインデックスセットはおそらくそれらの1つではないので、それを別のものに変換し、アーカイブし、目覚めたときにアーカイブを解除して再変換する必要があるということです.
次のコードを使用します
//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];