【问题标题】:iPhone MapKit multiple annotations issue. Is this the right way to proceed?iPhone MapKit 多个注释问题。这是正确的方法吗?
【发布时间】:2011-03-26 18:30:20
【问题描述】:

我正在尝试使用 MapKit 为 iPhone 开发我的第一个简单应用程序。我现在可以通过这个简单的代码在地图上显示多个注释。 MyAnnotation 是生成注解的类,initWithInfo 是设置坐标和标题的方法。

//the first annotation
theCoordinate.latitude = 0.000;
theCoordinate.longitude = 0.000;
MyAnnotation *myAnnotation1 = [MyAnnotation alloc];
[myAnnotation1 initWithInfo:theCoordinate:@"Title":@"Subtitle"];
[self.mapAnnotations insertObject:myAnnotation1 atIndex:0];
[myAnnotation1 release];

//the second annotation
theCoordinate.latitude = 0.000;
theCoordinate.longitude = 0.000;
MyAnnotation *myAnnotation2 = [MyAnnotation alloc];
[myAnnotation2 initWithInfo:theCoordinate:@"Title":@"Subtitle"];
[self.mapAnnotations insertObject:myAnnotation2 atIndex:0];
[myAnnotation2 release];

上面的代码需要为每个注解创建一个不同的 MyAnnotation 对象,但我需要在一个循环中生成它们,所以这种方式不太好。

为了生成尽可能多的注释而不限制创建具有唯一名称的对象,我尝试了以下代码,它工作正常。

CLLocationCoordinate2D theCoordinate;

//the first annotation
theCoordinate.latitude = 0.000;
theCoordinate.longitude = 0.000;
[self.mapAnnotations insertObject:[[MyAnnotation alloc] initWithInfo:theCoordinate:@"Title":@"Subtitle"] atIndex:0];

//the second annotation
theCoordinate.latitude = 0.000;
theCoordinate.longitude = 0.000;
[self.mapAnnotations insertObject:[[MyAnnotation alloc] initWithInfo:theCoordinate:@"Title":@"Subtitle"] atIndex:1];

现在简单的问题是:这是一种正确的方法吗?这段代码会导致任何问题吗?

提前感谢新手 Objective-c(想成为)程序员。

【问题讨论】:

    标签: iphone objective-c annotations mapkit


    【解决方案1】:

    是的,主要问题是第二个代码 sn-p 给您的应用程序添加了内存泄漏。另一个是它不会编译。

    当你将一个对象添加到集合中时,它的保留计数会增加,这意味着你的行

    [self.mapAnnotations insertObject:[[MyAnnotation alloc] initWithInfo:theCoordinate:@"Title":@"Subtitle"] atIndex:0];
    

    应该写成

    [self.mapAnnotations insertObject:[[[MyAnnotation alloc] initWithInfo:@"Title" theCoordinate:theCoordinate] autorelease] atIndex:0];
    

    注意两点:

    1. MyAnnotation 实例在发送到注释集合之前会发送一条“自动释放”消息。这是消除内存泄漏的一种方法。另一种是使用指针,就像之前的 sn-p 一样,然后像之前一样发送释放消息。
    2. 在Objective-C 中,参数不会在方法调用结束时全部放在一起。

    希望这会有所帮助!

    【讨论】:

    • 非常感谢您的解释:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多