2013-07-11 102 views
0

我是iOS編程新手。我創建視圖控制器具有的MKMapView元素,我想設置委託[mapView setDelegate:self]將代理設置爲MKMapView

首先,我的方法initWithNibName了這事包:喜歡:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     [[self map] setDelegate:self]]; 
     UITabBarItem *item = [[UITabBarItem alloc] init]; 
     [item setTitle:@"Map"]; 
     [self setTabBarItem:item]; 
    } 
    return self; 
} 

在這種情況下的MKMapView沒有給我任何消息,但當我將設置代理消息放置到viewDidLoad方法時,它工作正常。

有人可以解釋爲什麼它不工作時setting delegate messageinitWithNibName:bundle

回答

4

視圖不會在initWithNibName中加載,它只是初始化您的viewcontroller類並加載包含您的視圖細節的xib文件。

當viewcontroller調用viewDidLoad時,您將分配並初始化所有視圖對象。

在你的情況,當你在setDelegateinitWithNibname,您是在零值調用它,因此沒有得到確定,但在viewDidLoad MapView的分配和初始化,所以它工作正常。

爲了更深入的瞭解請參考:

http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/ViewLoadingandUnloading/ViewLoadingandUnloading.html

美麗的解釋在這裏:What is the process of a UIViewController birth (which method follows which)?

Looking to understand the iOS UIViewController lifecycle

http://thejoeconwayblog.wordpress.com/2012/10/04/view-controller-lifecycle-in-ios-6/

View Life-cycle

+0

Tnx很多。所以現在我知道何時viewcontroller對象被初始化=) –

1

這條線是你的問題:

[自圖]

initWithNibName地圖尚未初始化並返回零。

viewDidLoad地圖已經初始化。