在iPhone应用程序中设置属性时的奇怪行为
及 在PushOnStackViewController类的init方法中在iPhone应用程序中设置属性时的奇怪行为,iphone,Iphone,及 在PushOnStackViewController类的init方法中 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { PushOnStackViewController *vc = [[PushOnStackViewController alloc] init]; vc.key = [self.keys objectAtIndex:[
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
PushOnStackViewController *vc = [[PushOnStackViewController alloc] init];
vc.key = [self.keys objectAtIndex:[indexPath row]];
[self.navigationController pushViewController:vc animated:YES];
}
但是为什么我不能访问self.key?它返回null,即使它已被设置(它是一个字符串)
当我在viewDidLoad中访问它时,它会返回正确的值…任何我没有读过的内容,或者我做错了什么
提前感谢。您无法访问-init函数中的self.key,因为此时它尚未设置。您将在以后进行设置:
- (id)init {
self.navigationItem.title = key;
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"texts" ofType:@"plist"]];
self.keys = [dict objectForKey:key];
[dict release];
NSLog(@"%@", self.key);
NSLog(@"%i", [self.keys count]);
return self;
}
您可以尝试向init函数添加一个“key”参数,如下所示:
PushOnStackViewController *vc = [[PushOnStackViewController alloc] init]; // init runs here.
vc.key = [self.keys objectAtIndex:[indexPath row]]; // but you don't set the key property until here.
在设置属性之前,将调用init方法。去掉init方法,将代码移动到
viewDidLoad
中,以确保在完成所有属性设置后调用它
除非您知道自己在做什么,否则不要为
UIViewController
创建新的init方法。在viewDidLoad
方法中创建属性(如您所做)并访问该属性要容易得多。代码中的一个大问题是您通常首先初始化超类,即使用if((self=[super init]){…}返回self;在init方法中包装代码。否则,事情可能没有正确设置。initWithNibNamed:
是UIViewController
的指定初始值设定项,因此如果要添加自定义初始值设定项,需要覆盖该初始值设定项,或者确保调用它。
-(id)initWithKey:(NSString*)key {
self = [super init];
if (self) {
self.key = key;
...etc...
}
return self;
}