iphone - 实例变量在iOS应用程序中未保留值

标签 iphone objective-c ios scope instance-variables

我已经在我的体内声明了这个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/

相关文章:

ios - iPhone,将对象传递给方法,内存管理

ios - 在注册页面上遇到小写错误

objective-c - 将整数除以 float 时结果不正确

ios - 如何增加 UITableView 中自定义单元格的高度

ios - 如何更改标签栏项目与 View Controller 的关系?

iphone - Twitter 引擎 SA_OAuthTwitterEngine 集成?

iphone - 有没有办法为 UIImageView 对象的 z 位置设置某种 z 索引?

swift - 录制和播放音频可以在模拟器上工作,但不能在真实的 iPhone 设备上工作

iphone - iPhone 中的密码正则表达式?

objective-c - 多点触控和 ccTouchesMoved,移动滞后