NSMutableArray, pList, Tableview путаница и расплавление - PullRequest
0 голосов
/ 13 апреля 2011

У меня есть представление предпочтений, которое показывает другое представление таблицы в зависимости от того, какой сегментный элемент управления нажат.

Я жестко запрограммировал некоторые NSMutableArrays для проверки основных принципов:

prefsIssuesList = [[NSMutableArray alloc] init];
[prefsIssuesList addObject:@"Governance"];
[prefsIssuesList addObject:@"Innovation and technology"];
...etc

prefsIndustriesList = [[NSMutableArray alloc] init];
[prefsIndustriesList addObject:@"Aerospace and defence"];
... etc

prefsServicesList = [[NSMutableArray alloc] init];
[prefsServicesList addObject:@"Audit and assurance"];
...etc

currentArray = [[NSMutableArray alloc] init];
currentArray = self.prefsIssuesList;

Затем перезагрузите представление таблицы с помощью currentArray, добавив UITableViewCellAccessoryCheckmark. Все отлично работает.

Но теперь я хочу сохранить или выключить флажок в файле pList и прочитать его обратно.

В идеале хочу листать вот так

Root    Dictionary
    Issues  Dictionary
        Governance         Number   1
        Innovation and technology  Number   0
        etc

Я дошел до того, что решил это

// Designate plist file
NSString *path = [[NSBundle mainBundle] pathForResource: @"issues" ofType:@"plist"];
// Load the file into a Dictionary
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
self.allNames= dict;
[dict release];

NSLog(@"Dict is %@", allNames); // All the data in the pList file

NSMutableArray *issueSection = [allNames objectForKey:@"Issues"];
NSLog(@"Issues is %@", issueSection); // The data is the Issues Section

NSString *issueVal = [issueSection objectForKey:@"Governance"];
NSLog(@"Governance is %@", issueVal); //The value of the Governance key

Но что я действительно хочу сделать, так это перебрать словарь проблем и получить пары ключ / значение, чтобы

key   =  cell.textLabel.text
value =  UITableViewCellAccessoryCheckmark / UITableViewCellAccessoryNone 
         depending wether it's 1 or 0

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

Затем исправьте этот код, чтобы построить табличное представление

NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];

NSString *key = [keys objectAtIndex:section];
NSArray *nameSection = [names objectForKey:key];

static NSString *CellIdentifier = @"Cell";

//UITableViewCell *cell = [self.prefsTableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];
UITableViewCell *cell = [self.prefsTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
    cell=[[[UITableViewCell alloc] 
           initWithFrame:CGRectZero
           reuseIdentifier: CellIdentifier] autorelease];
}

cell.textLabel.text = [nameSection objectAtIndex:row];
return cell;

Но мой мозг растаял, сегодня я потратил около шести часов на чтение списков pLists, NSArrays, NSMutableDisctionaries, standardUserDefa, по-видимому, мало что дает.

Мне удалось использовать UITableViews внутри UINavigationViews, использовать SegmentedControls, загрузить асинхронный XML, но теперь я, наконец, застрял, или сгорел, или и то, и другое. Над тем, что должно быть довольно простыми парами ключ / значение.

Кто-нибудь хочет дать мне несколько идиотских указателей?

1 Ответ

0 голосов
/ 15 апреля 2011

Печатая это привело к другому сообщению с тем маленьким словом, которое мне нужно, чтобы вернуть меня в нужное русло:)

Использование пар ключ / значение в списке pList для указания имени ячейки и того, была ли она выбрана пользователем или нет.

plist основан на такой структуре

Root    Dictionary
        Services    Dictionary
                    Peaches       String    1
                    Pumpkin       String    0

Вот как я взял три массива Dictionary из pList и использовал пары ключ / значение для перезагрузки просмотра таблицы в зависимости от того, какой сегментControl был затронут:

- (void)viewDidLoad {
    [super viewDidLoad];

    // Designate plist file
    NSString *path = [[NSBundle mainBundle] pathForResource: @"issues" ofType:@"plist"];
    // Load the file into a Dictionary
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
    self.allNames= dict;
    [dict release];

    // Create the Named Dictionaries from Dictionary in pLIst
    NSMutableDictionary *allIssues = [self.allNames objectForKey:@"Issues"];
    self.prefsIssuesList = allIssues;
    [allIssues release];

    NSMutableDictionary *allIndustries = [self.allNames objectForKey:@"Industries"];
    self.prefsIndustriesList = allIndustries;
    [allIndustries release];

    NSMutableDictionary *allServices = [self.allNames objectForKey:@"Services"];
    self.prefsServicesList = allServices;
    [allServices release];

    // Assign the current Dictionary to out placeholder Dictionary 
    currentDict = [[NSMutableDictionary alloc] init];
    currentDict = self.prefsIssuesList;
}

Затем стилизация ячеек таблицы

- (UITableViewCell *)tableView:(UITableView *)prefsTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSUInteger row = [indexPath row];

    NSArray *keysArray = [self.currentDict allKeys];
    NSString *theKey = [keysArray objectAtIndex:row];
    NSString *theValue = [self.currentDict objectForKey: [keysArray objectAtIndex:row]];   

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [self.prefsTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil) {
        cell=[[[UITableViewCell alloc] 
               initWithFrame:CGRectZero
               reuseIdentifier: CellIdentifier] autorelease];
    }

    cell.textLabel.text = theKey;

    if (theValue == @"0") { 
        cell.accessoryType = UITableViewCellAccessoryNone; 
    }else { 
        cell.accessoryType = UITableViewCellAccessoryCheckmark; 
    } 

    return cell;
}

Предложение if в конце не работает, я опубликую его как новый вопрос (если никто не прокомментирует быстро!)

Наконец, сегменты управления ControlControls присваивают различные словари массиву заполнителей и перезагружают представление таблицы.

Это заняло у меня очень долгий день, чтобы понять (как нуби), поэтому я надеюсь, что это кому-то поможет

-(IBAction) segmentedControlIndexChanged{
switch (self.segmentedControl.selectedSegmentIndex) {
    case 0:
        //currentArray = self.prefsIssuesList;
        currentDict = self.prefsIssuesList;
        break;
    case 1:
        //currentArray = self.prefsIndustriesList;
        currentDict = self.prefsIndustriesList;
        break;
    case 2:
        //currentArray = self.prefsServicesList;
        currentDict = self.prefsServicesList;
        break;

    default:
        //currentArray = self.prefsIssuesList;
        currentDict = self.prefsIssuesList;
        break;
}
[prefsTableView reloadData];

} * * тысяча двадцать-один

Крик, если есть более аккуратный или лучший способ d

...