我已经在我的体内声明了这个ivar
ViewController.h
#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
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;
}
最佳答案
您将sortedCountries
重新声明为viewDidLoad
中的局部变量。用:
sortedCountries = ...
相反(注意no
NSArray *
)。在您现在使用的代码中,sortedCountries
将填充在viewDidLoad
中,但是可访问性仅可在viewDidLoad
中访问。您正在创建一个具有相同名称的新变量,而不是设置class属性。
关于iphone - 实例变量在iOS应用程序中未保留值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4879691/