2011-09-08 15 views
0

シミュレータでplistファイルを保存できましたが、Plistファイルをデバイスに保存できません。なにか提案を。plistを保存できません

私がファイルに書き込むためのファイル

[dict writeToFile:dictPath atomically: YES]; 

を読むために

NSString* dictPath = [[NSBundle mainBundle] pathForResource:@"Dictionary" ofType:@"plist"]; 
NSDictionary * dict = [[NSDictionary alloc] initWithContentsOfFile:dictPath]; 

を使用してメートル。

+0

メインバンドルは読んでいるだけですか?どのように私はr/wのアクセス場所にplistを保存するのですか? –

答えて

1

通常、ファイルに応じて〜/ Documentsまたは〜/ Libraryに保存します。質問What is the documents directory (NSDocumentDirectory)?には、これを理解するために必要なドキュメントのリンクとサンプルコードが含まれています。

1

あなたがメインバンドルに書き込むことはできません

NSDictionary * dict = [[NSDictionary alloc] initWithContentsOfFile:dictPath]; 
11

を読むために

NSString *mainBundlePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
NSString *dictPath = [mainBundlePath stringByAppendingPathComponent:@"Dictionary"]; 
NSDictionary * dict = ...; //Construct your dictionary 
[dict writeToFile:dictPath atomically: YES]; 

を書くためにDocumentsディレクトリに

をplistのを保存する必要があります。あなたはメインバンドルからしか読むことができません。ファイルを書きたい場合は、アプリケーションのドキュメントディレクトリに配置する必要があります。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",plistName]]; 

メインバンドルからplistが必要な場合は、最初にドキュメントディレクトリにコピーしてから変更することができます。一度しかコピーされていないことを確認することをお勧めします。

NSError *error; 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",plistName]]; 

NSFileManager *fileManager = [NSFileManager defaultManager]; 

if (![fileManager fileExistsAtPath: path]){ 
    NSLog(@"File don't exists at path %@", path); 

    NSString *plistPathBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"]; 

    [fileManager copyItemAtPath:plistPathBundle toPath: path error:&error]; 
}else{ 
    NSLog(@"File exists at path:%@", path); 
} 
+0

アプリが/アプリケーションフォルダにあるときに脱獄iPhoneで動作を停止します。 –

関連する問題