【问题标题】:Setting delegate to MKMapView将委托设置为 MKMapView
【发布时间】:2013-07-09 18:05:19
【问题描述】:

我是 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 messageinitWithNibName:bundle 中时它不起作用吗?

【问题讨论】:

    标签: ios objective-c delegates mkmapview viewcontroller


    【解决方案1】:

    这一行是你的问题:

    [自图]

    initWithNibName 中,映射尚未初始化,它返回 nil。

    viewDidLoad 中,地图已经初始化。

    【讨论】:

      【解决方案2】:

      视图不会在initWithNibName 中加载,它只是初始化您的视图控制器类并加载包含您的视图详细信息的 xib 文件。

      当 viewcontroller 调用viewDidLoad 时,您将分配并初始化所有视图对象。

      在您的情况下,当您在 initWithNibname 中使用 setDelegate 时,您在 nil 值上调用它,因此没有设置任何内容,但在 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/

      【讨论】:

      • Tnx 很多。所以现在我知道 viewcontroller 对象何时被初始化 =)
      猜你喜欢
      • 2019-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多