我遇到以下代碼的問題。正如你可以創建一個TripDetailsController(UIViewController的子類),並使用initWithNibName方法初始化這個TripDetailsController。這個initWithNibName需要一個額外的參數(tripDetails),參見下面的TripDetailsController類的代碼。變量td具有一個值,並且在遍歷代碼時,我檢查了在執行initWithNibName方法時在tdController上設置了此值。但是,在TripDetailsController.viewDidLoad方法(當調用pushViewController()時執行該方法)中設置斷點時,TripDetailsController的tripDetails屬性爲nil?!? 使用調試器我發現我在initWithNibName方法中看到的tdController實例與我在viewDidLoad方法中看到的實例是不同的實例?怎麼來的?爲什麼創建TripDetailsController的新實例以及由誰創建?UIViewController的第二個實例實例化,失去了在原始上完成的初始化。爲什麼?
在這篇文章的最後,我加入了一個調用棧的轉儲,也許這給了你一個提示這個問題的原因。
代碼:
// Code from RootViewController.getTripDetails() (see stacktrace below)
TripDetails td = ...; // td has a value
// Push the detail view controller
TripDetailsController *tdController = [[TripDetailsController alloc] initWithNibName:@"TripDetailsController" bundle:nil tripDetails:td];
// Checked using the debugger that tdController.tripDetails is set
[self.navigationController pushViewController:tdController animated:YES];
[tdController release];
代碼:
@implementation TripDetailsController
@synthesize tripDetails, expectedDurationLabel, normalDurationLabel;
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"Reis Details";
expectedDurationLabel.text = [NSString stringWithFormat:@"%@", tripDetails.expectedDuration];
}
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle tripDetails:(TripDetails *)td {
self = [self initWithNibName:nibName bundle:nibBundle];
self.tripDetails = td; // self.tripDetails has a value here!
[self.tripDetails retain];
return self;
}
- (void)dealloc {
[self.tripDetails release];
[super dealloc];
}
@end
alt text http://gerodt.homeip.net/stack.png
任何建議都歡迎。
呂
雖然無關,你不需要做[self.tripDetails保留]因爲,據推測,這個屬性被自動保留。 – 2009-06-19 18:43:47