实例变量在iOS应用程序中不保留值

我在我的身上宣布了这个伊娃

ViewController.h

#import  @interface FirstViewController : UIViewController  { NSArray *sortedCountries; } @property (nonatomic, retain) NSArray *sortedCountries; @end 

在ViewController.m中,sortedCountries通过存储已排序的.plist的结果来完成它的工作-(void)ViewDidLoad{}

什么时候

 -(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; } 

您正在viewDidLoad sortedCountries重新声明为局部变量。 使用:

 sortedCountries = ... 

相反(注意没有NSArray * )。 在您现在使用的代码中, sortedCountries将填充在viewDidLoad ,但只能viewDidLoad访问。 您正在创建具有相同名称的新变量,而不是设置类属性。

 NSArray *sortedCountries = [[countries sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]]retain]; 

 self.sortedCountries = [countries sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];