- (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];
}
and
in the init method of the PushOnStackViewController class I have
- (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;
}
But why can't I access the self.key? It returns null, even though it has been set(it is a string).
When I access it in viewDidLoad it returns the correct value...anything I haven't read, or am I doing anything wrong?
Thanks in advance.
You can't access self.key inside the -init function because at that point it hasn't been set yet. you are setting it afterwards:
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.
You might try adding a "key" parameter to the init function, like so:
-(id)initWithKey:(NSString*)key {
self = [super init];
if (self) {
self.key = key;
...etc...
}
return self;
}
Your init method is called before you set the property. Get rid of that init method and move your code into viewDidLoad
to ensure that it's called after you've done all the property setup.
Don't create new init method for a UIViewController
unless you know what you're doing. It's much easier to create a property (like you've done) and access that property inside the viewDidLoad
method.
精彩评论