2013-05-13 2 views
0

Я пытаюсь добавить и массив в массив Root в моем PLIST:Добавление массива в Plist

enter image description here

И не работает. Вот мой код:

-(IBAction)addName:(id)sender{ 
NSArray *arrayValues = [NSArray arrayWithObjects: nameLabel.text, nameDate.text, nameValue.text, nil]; 
NSString *plistpath = [[NSBundle mainBundle] pathForResource:@"Names" ofType:@"plist"]; 
NSMutableArray *namesNew = [[NSMutableArray alloc] initWithContentsOfFile:plistpath]; 
[namesNew addObject:arrayValues]; 
[namesNew writeToFile:plistpath atomically:YES]; 
} 

Что я делаю неправильно? Благодаря!

ответ

1

Вам необходимо переместить файл в NSDocumentDirectory. Затем отредактируйте файл plist.

Например:

Переход к NSDocumentDirectory:

-(NSDictionary *)copyBundleToDocuments 
{ 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [documentPaths objectAtIndex:0]; 
    NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:@"Names.plist"]; 
    NSString *bundlePath = [[NSBundle mainBundle] bundlePath]; 
    NSString *bundlePlistPath = [bundlePath stringByAppendingPathComponent:@"Names.plist"]; 

    //if file exists in the documents directory, get it 
    if([fileManager fileExistsAtPath:documentPlistPath]) 
    { 
     NSMutableDictionary *documentDict = [NSMutableDictionary dictionaryWithContentsOfFile:documentPlistPath]; 
     return documentDict; 
    } 
    //if file does not exist, create it from existing plist 
    else 
    { 
     NSError *error; 
     BOOL success = [fileManager copyItemAtPath:bundlePlistPath toPath:documentPlistPath error:&error]; 
     if (success) { 
      NSMutableDictionary *documentDict = [NSMutableDictionary dictionaryWithContentsOfFile:documentPlistPath]; 
      return documentDict; 
     } 
     return nil; 
    } 
} 

Тогда получите PLIST:

-(void)plistArray:(NSArray*)array 
    { 
     //get the documents directory: 
     NSArray *paths = NSSearchPathForDirectoriesInDomains 
     (NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 

     //getting the plist file name: 
     NSString *plistName = [NSString stringWithFormat:@"%@/Names.plist", 
           documentsDirectory]; 

     NSMutableArray *namesNew = [[NSMutableArray alloc] initWithContentsOfFile:plistName]; 

     [namesNew addObject:arrayValues]; 

     [namesNew writeToFile:plistName atomically:YES]; 

     return nil; 
    } 
+0

Не работает. Я понимаю ваш метод, но не знаю, почему он не работает. Я зарегистрировал 'documentsDirectory' и возвращает правильный путь к Names.plist, и файл находится там. Итак, я не знаю, что происходит. –

+0

может объяснить немного больше .. помочь .. что не сработало? – lakesh

+0

Написание. Он не писал. Все тот же файл. –

0

PLIST должен быть словарем в качестве базового объекта вместо массива.

NSMutableDictionary *namesNew = [NSMutableDictionary dictionaryWithContentsOfFile:plistpath]; 
[namesNew setObject: arrayValues forKey: @"Root"]; 
[namesNew writeToFile:plistpath atomically:YES]; 
+0

Не работает. То же самое. –

0

Вы не можете написать PLIST расслоению вам нужно использовать NSDocumentDirectory или NSCachesDirectory

Просто скопируйте PLIST в скрепляйте перезаписать.

Примечание: узнать разницу между NSCachesDirectory и NSDocumentDirectory https://developer.apple.com/icloud/documentation/data-storage/

Скопируйте PLIST из пучка к документам (в код ниже кэшей), вам нужно это только один раз, если ваш PLIST в вашей связке, я предпочитаю использовать этот код в appdelegate.m когда - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Names.plist"]; 
    NSString *[email protected]"Names.plist"; 

    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:plistInDocuments]; 

    NSError *error = nil; 
    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){ 
     [[NSFileManager defaultManager] copyItemAtPath:sourcePath 
               toPath:dataPath 
               error:&error]; 
    } 
    NSLog(@"Error description-%@ \n", [error localizedDescription]); 
    NSLog(@"Error reason-%@", [error localizedFailureReason]); 

Получите ваш файл и перезаписать его

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 
     NSString *[email protected]"Names.plist"; 
     NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:plistInDocuments]; 

     //add object here 
     NSMutableArray *namesNew = [[NSMutableArray alloc] initWithContentsOfFile:dataPath]; 
[namesNew addObject:arrayValues]; 

     NSError *error = nil; 
     if ([myFile writeToFile:dataPath options:NSDataWritingAtomic error:&error]) { 
      // file saved 
     } else { 
      // error writing file 
      NSLog(@"Unable to write plist to %@. Error: %@", dataPath, error); 
     } 
Смежные вопросы