невозможно сохранить plos ios - PullRequest
0 голосов
/ 09 сентября 2011

Я могу сохранить файл plist в симуляторе, но не могу сохранить файл Plist на устройстве.Любое предложение.

Я использую

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

для чтения файлов

и

[dict writeToFile:dictPath atomically: YES];

для записи в файл.

Ответы [ 3 ]

12 голосов
/ 10 сентября 2011

Вы не можете писать в основной пакет. Вы можете читать только из основного пакета. Если вы хотите написать файл, вам нужно поместить его в каталог документов вашего приложения.

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);
}
1 голос
/ 09 сентября 2011

Вам необходимо сохранить список в каталоге документов

для записи

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

для чтения

NSDictionary * dict = [[NSDictionary alloc] initWithContentsOfFile:dictPath];
1 голос
/ 09 сентября 2011

Как правило, вы можете хранить их в ~ / Documents или в ~ / Library в зависимости от файла.Вопрос Что такое каталог документов (NSDocumentDirectory)? содержит ссылки на документацию и пример кода, который вам необходим для понимания.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...