2014-10-29 2 views
0

Я пытаюсь добавить словарь в PLIST программно в следующем формате:Добавление словарей Plist программным

Root (Dict) | StringOfViewID (Dict) | ButtonTitle (Dict) | Строка Строка

Я могу это сделать, но я хочу продолжать добавлять в ViewID (Dict) больше ButtonTitle (Dict) под тем же ViewID (Dict).

До сих пор я могу заменить только существующие.

Что-то вроде этого:

Root (Dict) | StringOfViewID (Dict) - ButtonTitle (Dict) (2) -String String | ButtonTitle (Dict) (1) | Строка Строка

Вот код, я использую:

//Initialize and load the plist file here: 
[...] 
      NSMutableDictionary *data; 
      NSMutableDictionary *viewID; 
      NSMutableDictionary *buttonName; 
      NSArray *keys; 
      NSArray *locations; 


     // Insert the data into the plist 

     NSNumber *xNumber = [[NSNumber alloc] initWithDouble:locationX]; 
     NSNumber *yNumber = [[NSNumber alloc] initWithDouble:locationY]; 

     keys = [NSArray arrayWithObjects:@"locationX", @"locationY", nil]; 
     locations = [NSArray arrayWithObjects:xNumber, yNumber, nil]; 
     data = [NSMutableDictionary dictionaryWithObjects:locations forKeys:keys]; 
     buttonName = [NSMutableDictionary dictionaryWithObject:data forKey:myButtonTitle]; 
     viewID = [NSMutableDictionary dictionaryWithObject:buttonName forKey:@"StringOfViewID"]; 

     [viewID writeToFile:path atomically:YES]; 

Благодаря

+0

Я не совсем понимаю вашу структуру данных. Я думаю, у вас слишком много словарей. Похоже, вы можете просто добавлять словаря слова 'buttonName' в этот корневой словарь, и вам не нужен словарь« StringOfViewID ». – Paulw11

+0

Мне действительно нужны все словари. Я получаю идентификатор вида (т. Е. Тег), поэтому это другой словарь, который будет содержать много кнопок на каждом представлении, и каждая кнопка должна иметь свои координаты и имя.По крайней мере, это имеет смысл для меня, но если вы можете предложить лучший способ сделать, пожалуйста, сделайте так, как я немного потерял .... –

+0

Вы хотите добавить еще несколько кнопок после того, как вы прочтете файл plist обратно в память или просто в первый раз при создании файла? – Paulw11

ответ

1

Я бы создал класс, который будет служить моделью данных. Это простая реализация - это, вероятно, будет чище создать Button объект, а не передать несколько параметров и получить словарь

ViewButtons.h

@interface ViewButtons : NSObject 

+(ViewButtons *) viewButtonsWithContentsOfFile:(NSString *)file; 

-(void) addButton:(NSString *)buttonName withX:(double) x andY:(double) y toView:(NSString *)viewName; 
-(NSArray *)viewNames; 
-(NSArray *)buttonNamesForView:(NSString *)viewName; 
-(NSDictionary *)buttonWithName:(NSString *)name inView:(NSString *)viewName; 
-(void)writeToFile:(NSString *)file; 

@end 

ViewButtons.m

#import "ViewButtons.h" 

@interface ViewButtons() 

@property (nonatomic,strong) NSMutableDictionary *viewButtons; 

@end 

@implementation ViewButtons 

-(id) init { 
    if (self=[super init]) { 
     self.viewButtons=[NSMutableDictionary new]; 
    } 
    return self; 
} 

+(ViewButtons *) viewButtonsWithContentsOfFile:(NSString *)file { 
    ViewButtons *newViewButtons=[ViewButtons alloc]; 
    newViewButtons.viewButtons=[NSMutableDictionary dictionaryWithContentsOfFile:file]; 
    return newViewButtons; 
} 

-(void) addButton:(NSString *)buttonName withX:(double) x andY:(double) y toView:(NSString *)viewName { 
    NSMutableDictionary *viewDict=self.viewButtons[viewName]; 
    if (viewDict == nil) { 
     viewDict=[NSMutableDictionary new]; 
     self.viewButtons[viewName]=viewDict; 
    } else if (![viewDict isKindOfClass:[NSMutableDictionary class]]) { 
     viewDict=[viewDict mutableCopy]; 
     self.viewButtons[viewName]=viewDict; 
    } 
    NSNumber *xNumber = [NSNumber numberWithDouble:x]; 
    NSNumber *yNumber = [NSNumber numberWithDouble:y]; 
    NSDictionary *[email protected]{@"locationX":xNumber,@"locationY":yNumber}; 
    viewDict[buttonName]=buttonDict; 
} 


-(NSArray *)viewNames { 
    return self.viewButtons.allKeys; 
} 

-(NSArray *)buttonNamesForView:(NSString *)viewName { 
    return [self.viewButtons[viewName] allKeys]; 
} 
-(NSDictionary *)buttonWithName:(NSString *)name inView:(NSString *)viewName { 
    return self.viewButtons[viewName][name]; 
} 

-(void)writeToFile:(NSString *)file { 
    [self.viewButtons writeToFile:file atomically:YES]; 
} 

@end 

Вы можете использовать этот класс следующим образом:

ViewButtons *viewButtons=[ViewButtons viewButtonsWithContentsOfFile:buttonFile]; 
if (viewButtons == nil) { 
    viewButtons=[ViewButtons new]; 
} 

[viewButtons addButton:@"MyButton1" withX:0 andY:0 toView:@"MyView"]; 
[viewButtons addButton:@"MyButton2" withX:1 andY:1 toView:@"MyView"]; 
[viewButtons addButton:@"MyButton3" withX:0 andY:0 toView:@"MySecondView"]; 
[viewButtons addButton:@"MyButton4" withX:0 andY:1 toView:@"MyThirdView"]; 
[viewButtons writeToFile:buttonFile]; 
+0

спасибо мат. это сработало. –

2

Просто загрузите файл в первую NSMutableDictionary, внести изменения, которые вы хотите его, а затем записать его обратно файл с использованием того же кода, который вы используете уже.

Edit: Что касается структуры вы используете для редактирования списка, вы можете иметь множество кнопок словарей

NSMutableDictionary* oldDictionary=[NSMutableDictionary dictionaryWithContentsOfFile:path]; 

    // make the new button dictionary 
    NSNumber *xNumber = [[NSNumber alloc] initWithDouble:locationX]; 
    NSNumber *yNumber = [[NSNumber alloc] initWithDouble:locationY]; 

    NSDictionary*[email protected]{@"locationX": xNumber, 
            @"locationY":yNumber, 
            @"myButtonTitle":myButtonTitle}; 
    NSMutableArray *buttonsArray = [oldDictionary objectForKey:@"StringOfViewID"]; 
    //append it to the array 
    [buttonsArray addObject:buttonDictionary]; 
    //replace the old array with the new one 
    [oldDictionary setObject:buttonsArray forKey:@"StringOfViewID"]; 
    //write it back to the file 
    [oldDictionary writeToFile:path atomically:YES]; 

Или словарь пуговиц словарей

NSMutableDictionary* oldDictionary=[NSMutableDictionary dictionaryWithContentsOfFile:path]; 

    // make the new button dictionary 
    NSNumber *xNumber = [[NSNumber alloc] initWithDouble:locationX]; 
    NSNumber *yNumber = [[NSNumber alloc] initWithDouble:locationY]; 

    NSDictionary*[email protected]{@"locationX": xNumber, @"locationY":yNumber}; 
    NSMutableDictionary *buttonsDictionary = [oldDictionary objectForKey:@"StringOfViewID"]; 
    //add it to the dictionary 
    [buttonsDictionary setObject:buttonLocationDictionary forKey:myButtonTitle];//be sure that this is a new button title,or else it will replace the old value with this title. 

    //replace the old dictionary with the new one 
    [oldDictionary setObject:buttonsDictionary forKey:@"StringOfViewID"]; 
    //write it back to the file 
    [oldDictionary writeToFile:path atomically:YES]; 

Я пытался не изменить структуру или ключи, которые вы используете, и я предположил, что StringOfViewID - это ключ, который будет иметь все кнопки в текущем представлении интересов, а другие виды будут иметь другие ключи.

+0

Я попытался скопировать его, а затем сделать следующее: [viewID copy]; newViewID = [NSMutableDictionary mutableCopy]; , но я получаю сбой. –

+0

, тогда я пробовал: NSMutableDictionary * dictionaryWithExistingKey = [viewID objectForKey: @ "StringOfViewID"]; NSMutableDictionary * словарьOldAndNewItems = [NSMutableDictionary dictionaryWithDictionary: dictionaryWithExistingKey]; [словарьOldAndNewItems addEntriesFromDictionary: buttonName]; [newViewID setObject: dictionaryOldAndNewItems forKey: @ "StringOfViewID"]; [newViewID writeToFile: path atomically: YES], но ничего не происходит –

+0

'addEntriesFromDictionary' заменит старое значение новым значением, пока вы используете тот же ключ. Вам нужно вставить новое 'buttonName' с помощью нового ключа или сделать массив имен кнопок под тем же ключом. Я могу предоставить вам пример кода, если я не проясню его. –

Смежные вопросы