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

moz*_*zer 1 iphone scope objective-c instance-variables ios

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

ViewController.h

#import <UIKit/UIKit.h>

@interface FirstViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

{   
NSArray *sortedCountries;       
}

@property (nonatomic, retain) NSArray *sortedCountries;

@end
Run Code Online (Sandbox Code Playgroud)

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

什么时候

-(UITableViewCell *)tableView:(UITableView *)tableView
        cellForRowAtIndexPath:(NSIndexPath *)indexPath {}
Run Code Online (Sandbox Code Playgroud)

在下面调用,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;
} 
Run Code Online (Sandbox Code Playgroud)

0x8*_*00d 6

NSArray *sortedCountries = [[countries sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]]retain];
Run Code Online (Sandbox Code Playgroud)

self.sortedCountries = [countries sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];
Run Code Online (Sandbox Code Playgroud)