NSMutableArray работает в ViewDidLoad, но не в DidSelectRowAtIndexPath - PullRequest
1 голос
/ 22 сентября 2011

Menu.h

@interface Menu : UITableViewController {    
    NSMutableArray *arrayCellCollectionOrder;
    NSMutableDictionary *dictCellCollection;
    NSMutableDictionary *dictCellIndividual;
}

@property (nonatomic, retain) NSMutableArray *arrayCellCollectionOrder;

@end

Menu.m

ViewDidLoad работает как обычно.

@synthesize arrayCellCollectionOrder;

- (void)viewDidLoad {

    // Codes to read in data from PLIST
    // This part works

    NSString *errorDesc = nil;
    NSPropertyListFormat format;
    NSString *plistPath;
    NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    plistPath = [rootPath stringByAppendingPathComponent:@"InfoTableDict.plist"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
        plistPath = [[NSBundle mainBundle] pathForResource:@"InfoTableDict" ofType:@"plist"];
    }

    NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
    NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization
                                        propertyListFromData:plistXML
                                        mutabilityOption:NSPropertyListMutableContainersAndLeaves
                                        format:&format
                                        errorDescription:&errorDesc];

    if (!temp) {
        NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
    }

    arrayCellCollectionOrder = [[[NSMutableArray alloc] init] retain];
    arrayCellCollectionOrder = [temp objectForKey:@"CellCollectionOrder"]; 

    // I can access `arrayCellCollectionOrder` here, it's working.

}

cellForRowAtIndexPath работает как обычно.Я могу получить доступ к arrayCellCollectionOrder.

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

    static NSString *CellIdentifier = @"PhotoCell";
    PhotoCell *cell = (PhotoCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"PhotoCell" owner:self options:nil];
        for (id currentObject in topLevelObjects) {
            if ([currentObject isKindOfClass:[PhotoCell class]]) {
                cell = (PhotoCell *) currentObject;
                break;
            }
        }
    }

    // Copy the specific dictionary from CellCollection to Cell Individual
    dictCellIndividual = [dictCellCollection objectForKey:[NSString stringWithFormat:@"%@", [arrayCellCollectionOrder objectAtIndex:indexPath.row]]];

    cell.photoCellTitle.text = [dictCellIndividual objectForKey:@"Title"];     // Load cell title
    cell.photoCellImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@", [dictCellIndividual objectForKey:@"ThumbnailFilename"]]];        // Load cell image name

    return cell;

}

didSelectRowAtIndexPath НЕ РАБОТАЕТ.Я не могу получить доступ к arrayCellCollectionOrder.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

// Browser
NSMutableArray *arrayPhotos = [[NSMutableArray alloc] init];

    NSLog(@"indexPath.row = %d", indexPath.row);        // Returns the row number i touched, works.

    NSLog(@"arrayCellCollectionOrder = %@", [NSString stringWithFormat:@"%@", [arrayCellCollectionOrder objectAtIndex:indexPath.row]]);        // DOES NOT WORK.

    // Copy the specific dictionary from CellCollection to Cell Individual
    dictCellIndividual = [dictCellCollection objectForKey:[NSString stringWithFormat:@"%@", [arrayCellCollectionOrder objectAtIndex:indexPath.row]]];        // This similar line gives error too.

    ...   ...
    ...   ...
    ...   ...
    ...   ...

}

Ошибка: * Завершение работы приложения из-за необработанного исключения 'NSRangeException', причина: '- [__ NSCFArray objectAtIndex:]: index (1)за пределами (0) '

, т. е. я щелкнул по строке 1, но arrayCellCollectionOrder имеет значение NULL.В arrayCellCollectionOrder должны быть данные, как они объявлены в ViewDidLoad.

Есть что-то, что я пропустил?Заранее большое спасибо.

1 Ответ

0 голосов
/ 22 сентября 2011
arrayCellCollectionOrder = [[[NSMutableArray alloc] init] retain];
arrayCellCollectionOrder = [temp objectForKey:@"CellCollectionOrder"]; 

Вы видите, что вы делаете с arrayCellCollectionOrder? Сначала вы назначаете его новому NSMutableArray (и сохраняете его без необходимости), а затем немедленно теряете массив и присваиваете arrayCellCollectionOrder другому объекту, который вы получаете из словаря temp. Другими словами, эта первая строка ничего не делает для вас, кроме создания пропущенного изменяемого массива.

Если вторая строка верна, и вы получаете действительный объект, и это то, что вы хотите, тогда проблема в том, что я не вижу, где этот объект сохраняется. Пока он находится в словаре, он, вероятно, сохраняется, но если temp отбрасывается, то его члены освобождаются. Если вы сделали

self.arrayCellCollectionOrder = [temp objectForKey:@"CellCollectionOrder"];

тогда установщик сохранит его.

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