2009-10-29 17 views
6

私はこれがうまくいくと思っていましたが、今はartistCollectionが "Artist"オブジェクトのNSMutableArrayであるため、それはできません。オブジェクトのNSMutableArrayをディスクに保存/書き込みしますか?

@interface Artist : NSObject { 
    NSString *firName; 
    NSString *surName; 
} 

私の質問は、私は彼らに私は自分のアプリケーションを実行して、次回を読み込むことができるようにディスクに「アーティスト」オブジェクトの私NSMutableArrayのを記録する最良の方法は何かありますか?ただ一つ、最終的なもの

artistCollection = [[NSMutableArray alloc] init]; 

newArtist = [[Artist alloc] init]; 
[newArtist setFirName:objFirName]; 
[newArtist setSurName:objSurName]; 
[artistCollection addObject:newArtist]; 

NSLog(@"(*) - Save All"); 
[artistCollection writeToFile:@"/Users/Fgx/Desktop/stuff.txt" atomically:YES]; 

EDIT

多くのおかげで、私は好奇心です。 "Artist"にさらにオブジェクト(アプリケーション)のNSMutableArray(softwareOwned)の余分なインスタンス変数が含まれている場合、これをカバーするためにどのようにエンコードを拡張しますか? NSCodingを "Applications"オブジェクトに追加してから、 "Artist"をエンコードする前にエンコードするか、 "Artist"でこれを指定する方法はありますか?

@interface Artist : NSObject { 
    NSString *firName; 
    NSString *surName; 
    NSMutableArray *softwareOwned; 
} 

@interface Application : NSObject { 
    NSString *appName; 
    NSString *appVersion; 
} 

多くのおかげ

ゲイリー

+0

:ちょうどあなたのアプリケーションクラスにNSCodingを実装する。これにより

@interface Artist : NSObject <NSCoding> { NSString *firName; NSString *surName; } @end @implementation Artist static NSString *FirstNameArchiveKey = @"firstName"; static NSString *LastNameArchiveKey = @"lastName"; - (id)initWithCoder:(NSCoder *)decoder { self = [super init]; if (self != nil) { firName = [[decoder decodeObjectForKey:FirstNameArchiveKey] retain]; surName = [[decoder decodeObjectForKey:LastNameArchiveKey] retain]; } return self; } - (void)encodeWithCoder:(NSCoder *)encoder { [encoder encodeObject:firName forKey:FirstNameArchiveKey]; [encoder encodeObject:surName forKey:LastNameArchiveKey]; } @end 

、あなたは、コレクションをエンコードすることができますアーティストのencodeWithCoder:およびinitWithCoder:では、変更可能な配列のエンコード/デコードを処理する行を追加します。エンコードするように要求されると、配列はアプリケーションオブジェクトにエンコードを要求します。 –

+0

ああ、私は、完璧、オレに感謝を参照してください。 – fuzzygoat

答えて

18

writeToFile:atomically:を見ますコレクションクラスはプロパティリスト、つまりNSString、NSNumber、その他のコレクションなどの標準オブジェクトを含むコレクションに対してのみ機能します。

jdelStrother's answerで詳述すると、コレクションに含まれるすべてのオブジェクトが自分自身でアーカイブできる場合は、NSKeyedArchiverを使用してコレクションをアーカイブできます。カスタムクラスのためにこれを実装するには、それはNSCodingプロトコルに準拠します:あなたの編集に答えるために

NSData* artistData = [NSKeyedArchiver archivedDataWithRootObject:artistCollection]; 
[artistData writeToFile: @"/Users/Fgx/Desktop/stuff" atomically:YES]; 
9

はNSKeyedArchiverを見てみましょう。簡単に言えば:

NSData* artistData = [NSKeyedArchiver archivedDataWithRootObject:artistCollection]; 
[artistData writeToFile: @"/Users/Fgx/Desktop/stuff" atomically:YES]; 

あなたはencodeWithCoderを実装する必要があります:あなたのアーティストのクラスに - Apple's docs

アーカイブ解除は(NSKeyedUnarchiverを参照)読者の練習として残して:)

Cocoaの中
関連する問題