3
-(void)login{
    NSBundle *bundle = [NSBundle mainBundle];
    NSString *path = [bundle pathForResource:@"login" ofType:@"plist"];

    NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];

    [plistDict setObject:@"si" forKey:@"stato"];

    [plistDict writeToFile:path atomically: YES];
}

iOS シミュレータでは plist は正しく記述されていますが、iPhone で .plist を記述しようとすると、うまくいきません。間違った .plist パスが原因だと思います。iOS デバイスは別のパスを使用しますか?

4

5 に答える 5

5

最初に、ドキュメント ディレクトリにファイルが存在するかどうかを確認する必要があります。そこに存在しない場合は、ドキュメント ディレクトリにコピーできます。このようにできます

-(void)login{
    BOOL doesExist;
    NSError *error;
    NSString *filePath= [[NSBundle mainBundle] pathForResource:@"login" ofType:@"plist"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString * path =[[NSString alloc] initWithString:[documentsDirectory stringByAppendingPathComponent:@"login.plist"]];

    doesExist= [fileManager fileExistsAtPath:path];
    if (doesExist) {
        NSMutableDictionary* plistDict=[[NSMutableDictionary alloc] initWithContentsOfFile:path];                
    }
    else
    {    

        doesExist= [fileManager copyItemAtPath:filePath  toPath:path error:&error];
        NSMutableDictionary* plistDict=[[NSMutableDictionary alloc] initWithContentsOfFile:filePath];        
    }  

    [plistDict setObject:@"si" forKey:@"stato"];

    [plistDict writeToFile:path atomically: YES];
}
于 2012-09-02T15:03:51.263 に答える
2

[NSBundle mainBundle] の場所に書き込むことはできません。plist のようなファイルを書き込むには、次のようにドキュメント フォルダーに保存する必要があります。

NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *filePathToSave = [arrayPaths objectAtIndex:0];

plist がアプリの一部である場合は、最初の起動時に、同じ を使用して既にドキュメント フォルダーにコピーしておくことをお勧めします。filePathToSaveそうすれば、読み取りと保存の両方で常にそこに表示されます。

于 2012-09-02T14:25:00.883 に答える
1

メイン バンドルのみが読み取り可能であり、コンパイル時に App Bundle でのみ構成されるため、これは大きな間違いです。App Bundle は別の場所にありますが、ディスクに書き込む必要があるデータは、サンドボックスの Documents、Temporary、または Library フォルダーに配置する必要があります。

さらに理解を深めるには、公式のFile System Programming Guideをお読みください。
あなたが知る必要があるすべてがそこに書かれています。
サブフォルダーに書き込むこともできます。iTunes または iCloud と同期する場合、バックアップに関しては、上記の 3 つのメイン ディレクトリから選択する必要があります。たとえば、tmp フォルダーの内容はバックアップされません。

于 2012-09-02T14:57:06.053 に答える
0

iOSデバイスでmainBundleに書き込むことはできません。ファイルをディレクトリに保存し、そこで変更する必要があります。

于 2012-09-02T14:17:23.377 に答える
0

答えを現代の世界に持ち込むためだけに、ディレクトリを取得するために URL ベースの方法を実際に使用する必要があります。

NSFileManager *fileManager = [[NSFileManager alloc] init];

NSURL *URLForDocumentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]
于 2012-09-02T14:32:29.040 に答える