将委托设置为MKMapView

时间:2013-07-11 12:51:00

标签: ios objective-c delegates mkmapview viewcontroller

我是iOS编程新手。我用MKMapView元素创建了ViewController,我想设置委托[mapView setDelegate:self]

首先我在方法initWithNibName中完成了:bundle:like:

- (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 message initWithNibName:bundle时,有人可以解释为什么它无效吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

这一行是你的问题:

  

[自我地图]

initWithNibName中,地图尚未初始化,并返回nil。

viewDidLoad中,地图已初始化。