1

さまざまなカスタム オブジェクトがあるプロジェクトに取り組んでいます。これらのカスタム オブジェクト (ネストされた可変配列で機能するものもあります) は、ファイルに保存する必要があります。そうするための最良のアプローチは何ですか?読み込みと保存のファイル マネージャーを作成する必要がありますか?それとも、各オブジェクトに処理させる方がよいでしょうか?

お時間をいただきありがとうございます。

-- スティーブン

4

3 に答える 3

1

クラスのプロトコルを実装NSCodingします。

NSString * const kMyArray = @"myString";
NSString * const kMyBool = @"myBool";

- (void)encodeWithCoder:(NSCoder *)coder
{
    [coder encodeObject:_myArray forKey:kMyArray];
    [coder encodeBool:_myBool forKey:kMyBool];
    //...
}

- (id)initWithCoder:(NSCoder *)coder
{
    self = [super init];
    if (self) {
        _myArray = [coder decodeObjectForKey:kMyArray];
        _myBool = [coder decodeBoolForKey:kMyBool];
        //...
    }
    return self;
}

これにより、次の方法でデータを保存およびロードできますNSKeyedArchiver

//saving collection of Class<NSCoding> objects
NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
BOOL success = [NSKeyedArchiver archiveRootObject:_collection toFile:path];

//loading
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
if (data) _collection = [NSKeyedUnarchiver unarchiveObjectWithData:data];
于 2012-10-26T08:30:48.213 に答える
0

オブジェクトをエンコードおよびデコードする場合は、NSCoding を参照してください。これは単純明快なアプローチです。

ドキュメントをご覧ください: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSCoding_Protocol/Reference/Reference.html (正しいリンクを編集)

iOS のバージョンを更新すると、保存されたオブジェクトが破損するという問題が発生しました。iOS 4.1 から iOS 4.2 への移行の頃でした。

私は NSCoder の使用をやめ、基になる JSON ファイルを持つカスタム ファイル形式の作成に切り替えました。これで、ファイルのバージョン管理をより細かく制御できるようになり、修正も簡単に行うことができます。これは、自分のデータ ファイルを解釈することがすべてであるためです。

于 2012-10-26T08:30:59.070 に答える
0

アプリ バンドルにplist ファイル ( Config.plistが plist の名前であるとします) を手動で作成し、ドキュメント ディレクトリにコピーした後、プログラムで変更することができます。

ファイルをドキュメント ディレクトリにコピーする方法をここで確認してください。まず、2 つのマクロを定義します。

#define DOCUMENT_DIR        [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]
#define PLIST_SETTINGS      [DOCUMENT_DIR stringByAppendingPathComponent:@"Config.plist"]

その後 -

 NSString *configPath = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"];
[self copyIfNeededFrom:configPath To:PLIST_SETTINGS];
 NSMutableArray* mArrObjects = [NSMutableArray alloc] initWithObjects:obj1,obj2,obj3, nil];
[mArrObjects writeToFile:PLIST_SETTINGS atomically:YES];
[mArrObjects release];

次に、 copyIfNeededFrom:の定義を次のように指定します。

- (BOOL)copyIfNeededFrom:(NSString *)sourcePath To:(NSString *)destinationPath
{
NSError *error = noErr;
if(![[NSFileManager defaultManager] fileExistsAtPath:destinationPath])
{
    [[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destinationPath error:&error];
}
if(noErr)
    return YES;
else
    return NO;
}

それがうまくいくことを願っています。乾杯!!!

于 2012-10-26T08:43:11.890 に答える