Сохранение и получение нескольких словарей в файл plist - PullRequest
0 голосов
/ 11 января 2011

Так как я новичок в программировании для iPhone и пытаюсь разобраться во всем, у меня возникла проблема, когда я пытаюсь сохранить словарь в plist в следующем формате ...

-Root
    -StateName (Dictionary)
        - TitleOfLocation (Dictionary)
            -Address (String)
            -City (String)
            -State (String)

Может быть, я здесь полностью или логика должна быть изменена, но, в конце концов, мне нужно заполнить ее в UITableView, отсортированном по имени состояния.

В настоящее время я могу сохранить данные в одном словаре, записать их в PLST и перетащить в UITableView (основы, да, я знаю), но, как я уже сказал, у меня просто проблемы с сохранением вложенных словарей.

Кто-нибудь сможет направить меня в правильном направлении? Спасибо.

1 Ответ

0 голосов
/ 11 января 2011

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

- Root (array) 
 - Texas (array) 
  - Location1 (dictionary)
   - TitleOfLocation (string)
   - Address (string)
   - ...
 - Florida (array)
  - Location1 (dictionary)
   - ...
  - Location2 (dictionary)
   - ...
// and
- StateNames (array)
 - Texas (string)
 - Florida (string)

Для удобства вы можете поместить эти два массива в один NSDictionary.Я не делал этого в моем примере.
И поскольку NSArray, NSDictionary и NSString все подтверждают протокол NSCoding, вы можете записать этот словарь на диск с помощью writeToFile: atomically:

Я написал пример кода дляВы, потому что я думаю, что решение довольно простое, но трудно описать словами.

#define kKeyDescription @"kKeyDescription"
#define kKeyAddress     @"kKeyAddress"
#define kKeyCity        @"kKeyCity"
#define kKeyState       @"kKeyState"

- (void)viewDidLoad {
    [super viewDidLoad];
    NSMutableArray *root = [NSMutableArray array];
    NSMutableArray *sectionTitle = [NSMutableArray array];

    NSMutableArray *florida = [NSMutableArray array];
    [root addObject:florida];
    [sectionTitle addObject:@"Florida"];

    NSMutableArray *texas = [NSMutableArray array];
    [root addObject:texas];
    [sectionTitle addObject:@"Texas"];

    NSDictionary *location1 = [NSDictionary dictionaryWithObjectsAndKeys:
                               @"My favorite pizza place", kKeyDescription,
                               @"5106 Grace Drive", kKeyAddress,
                               @"Miami", kKeyCity,
                               @"Florida", kKeyState,
                               nil];
    [florida addObject:location1];

    NSDictionary *location2 = [NSDictionary dictionaryWithObjectsAndKeys:
                               @"Home", kKeyDescription,
                               @"1234 Foobar Street", kKeyAddress,
                               @"Fort Lauderdale", kKeyCity,
                               @"Florida", kKeyState,
                               nil];
    [florida addObject:location2];

    NSDictionary *location3 = [NSDictionary dictionaryWithObjectsAndKeys:
                               @"Franks Workplace", kKeyDescription,
                               @"9101 Baz Avenue", kKeyAddress,
                               @"Houston", kKeyCity,
                               @"Texas", kKeyState,
                               nil];
    [texas addObject:location3];

    data = [root retain];
    sectionData = [sectionTitle retain];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.data count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [self.sectionData objectAtIndex:section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[self.data objectAtIndex:section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellID = @"MyCellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID] autorelease];
    }
    NSDictionary *object = [[self.data objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    //                      < This is the array for the selected state >
    cell.textLabel.text = [object valueForKey:kKeyDescription];
    cell.detailTextLabel.text = [object valueForKey:kKeyAddress];
    return cell;
}
...