Переменная экземпляра не сохраняет значение в приложении iOS

Я объявил этот ивар в моем

ViewController.h

#import <UIKit/UIKit.h>

@interface FirstViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

{   
NSArray *sortedCountries;       
}

@property (nonatomic, retain) NSArray *sortedCountries;

@end

В ViewController.m sortedCountries выполняет свою работу в -(void)ViewDidLoad{}, сохраняя результат отсортированного .plist.

Когда

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

вызывается ниже, sortedCountries возвращает (null)

Почему значение sortedCountries не сохраняется? Я добавил retain в первую функцию... Я думаю, что здесь мне не хватает фундаментального арендатора Objective-C.

ViewController.m

#import "FirstViewController.h"

@implementation FirstViewController

@synthesize sortedCountries;

-(void)viewDidLoad  {

NSString *path = [[NSBundle mainBundle] pathForResource:@"countries" ofType:@"plist"];  
NSArray *countries = [NSArray arrayWithContentsOfFile:path];
NSSortDescriptor *descriptor = [[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] autorelease];
NSArray *sortedCountries = [[countries sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]]retain];

}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}

-(NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {

return 236; 
}

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

NSDictionary *country = [sortedCountries objectAtIndex:indexPath.row];
NSLog(@"countryDictionary is: %@",country);
NSString *countryName = [country objectForKey:@"name"];
NSLog(@"countryName is : %@", countryName);

    static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                   reuseIdentifier:CellIdentifier] autorelease];

}

cell.textLabel.text = countryName;
return cell;
} 

person mozzer    schedule 02.02.2011    source источник


Ответы (1)


Вы повторно объявляете sortedCountries как локальную переменную в viewDidLoad. Использовать:

sortedCountries = ...

вместо этого (обратите внимание № NSArray *). В коде, который вы используете сейчас, sortedCountries будет заполнено в viewDidLoad, но доступно только в viewDidLoad. Вы создавали новую переменную с тем же именем вместо установки свойства класса.

person Evan Mulawski    schedule 02.02.2011
comment
Спасибо за подробное объяснение. - person mozzer; 03.02.2011