问题描述
我已经在我的
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的结果。
In ViewController.m, sortedCountries does it's job in -(void)ViewDidLoad{}
by storing the result of a sorted .plist.
当
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {}
在下面调用,sortedCountries返回(null)
is called below, sortedCountries returns (null)
为什么sortedCountries的值不存在?我在第一个函数中添加了一个 retain
...我想我在这里缺少一个基本的Objective-C租户。
Why doesn't the value of sortedCountries remain? I added a retain
in the first function... I think I am missing a fundamental Objective-C tenant here.
ViewController.m
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;
}
推荐答案
您正在重新声明 sortedCountries
作为 viewDidLoad
中的局部变量。使用:
You are re-declaring sortedCountries
as a local variable in viewDidLoad
. Use:
sortedCountries = ...
相反(注意没有 NSArray *
)。在您现在使用的代码中, sortedCountries
将填入 viewDidLoad
,但只能访问 在 viewDidLoad
中。您正在创建一个具有相同名称的新变量,而不是设置类属性。
instead (notice no NSArray *
). In the code you are using now, sortedCountries
would be populated in viewDidLoad
, but accessible only in viewDidLoad
. You were creating a new variable with the same name instead of setting the class property.
这篇关于实例变量在iOS应用程序中不保留值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!