0

現在、アプリにゲーム保存機能を追加しようとしています。最終的な目標は、約 300 個のカスタム オブジェクトを.plistファイルに保存し、後で再度抽出することです。ある程度は前進しましたが、いくつか問題がinitWithCoder:あり、自分のテクニックについても確信が持てません。

次のコードはUIViewController、オブジェクトを保存するために使用されています (例として、2 つのオブジェクトのみを辞書に追加しました)。

//Saves the contents to a file using an NSMutableDictionary
-(IBAction)saveContents {

    //Create the dictionary
    NSMutableDictionary *dataToSave = [NSMutableDictionary new];

    //Add objects to the dictionary
    [dataToSave setObject:label.text forKey:@"label.text"];
    [dataToSave setObject:territory forKey:@"territory"];
    [dataToSave setObject:territory2 forKey:@"territory2"];

    //Archive the dictionary and its contents and set a BOOL to indicate if it succeeds
    BOOL success = [NSKeyedArchiver archiveRootObject:dataToSave toFile:[self gameSaveFilePath]];

    //Handle success/failure here...

    //Remove and free the dictionary
    [dataToSave removeAllObjects]; dataToSave = nil;
}

これにより、クラスencodeWithCoder:内の関数が2 回正常に呼び出されます。Territory

-(void)encodeWithCoder:(NSCoder *)aCoder {

    NSLog(@"ENCODING");
    [aCoder encodeObject:self.data forKey:@"data"];
    [aCoder encodeInt:self.MMHValue forKey:@"MMHValue"];
    [aCoder encodeObject:self.territoryName forKey:@"territoryName"];
    //Continue with other objects
}

ディレクトリを調べると、確かにファイルが存在します。さて、私が抱えている問題は次のとおりです。次の関数を実行すると、initWithCoder:関数が正常に 2 回呼び出されます。関数内のログinitWithCoder:は本来あるべきものを出力しますが、 の関数内のログはUIViewController、などをloadContents返します。ただし、ラベルのテキストは正しく設定されています。0null

//Loads the contents from a file using an NSDictionary
-(IBAction)loadContents {

    //Create a dictionary to load saved data into then load the saved data into the dictionary
    NSDictionary *savedData = [NSKeyedUnarchiver unarchiveObjectWithFile:[self gameSaveFilePath]];

    //Load objects using the dictionary's data
    label.text = [savedData objectForKey:@"label.text"];

    NSLog(@"%i, %i", [territory intAtKey:@"Key4"], [territory2 intAtKey:@"Key4"]);
    NSLog(@"MMH: %i, %i", territory.MMHValue, territory2.MMHValue);
    NSLog(@"NAME: %@, %@", territory.territoryName, territory2.territoryName);

    //Free the dictionary
    savedData = nil;
}

- (id)initWithCoder:(NSCoder *)aDecoder {

    if (self = [super initWithCoder:aDecoder]) {

        NSLog(@"DECODING TERRITORY");

        self.data = [aDecoder decodeObjectForKey:@"data"];
        self.MMHValue = [aDecoder decodeIntForKey:@"MMHValue"];
        self.territoryName = [[aDecoder decodeObjectForKey:@"territoryName"] copy];
        //Continue with other objects
    }

    NSLog(@"DECODED INT: %i", self.MMHValue);
    NSLog(@"DECODED NAME: %@", self.territoryName);
    return self;
}

これを何時間も機能させようとしましたが、役に立ちませんでした。誰かがこれについて何か洞察を持っているなら、私を助けてください。また、保存するための私のテクニックが良いかどうかは完全にはわかりません( を使用しNSMutableDictionaryてオブジェクトへの参照を保存し、1つのファイルに出力できるようにします)?ありがとう!

4

1 に答える 1