2011-03-26 7 views
1

나는 MapKit을 사용하여 iPhone 용 첫 번째 간단한 앱을 개발하려고합니다. 이 간단한 코드로지도에 여러 주석을 표시 할 수있게되었습니다. MyAnnotation은 주석을 생성하는 클래스이고 initWithInfo는 좌표와 제목을 설정하는 메소드입니다.iPhone MapKit 다중 주석 문제. 이것이 올바른 진행 방법입니까?

//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]; 

이제 쉬운 질문은 :가 진행하는 올바른 방법인가? 이 코드가 어떤 종류의 문제를 일으킬 수 있습니까?

미리 newbie objective-c (원하실) 프로그래머에게 감사드립니다.

답변

1

예, 주요 문제는 두 번째 코드 조각이 응용 프로그램에 메모리 누수를 추가했기 때문입니다. 다른 하나는 컴파일되지 않는다는 것입니다.

: 당신이 당신의 라인

[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 인스턴스는 주석 컬렉션에 보내기 전에 "autorelease"메시지를 보냅니다. 이것은 메모리 누수를 제거하는 한 가지 방법입니다. 다른 하나는 이전 스 니펫 에서처럼 포인터를 사용하고 이전에했던 것처럼 릴리스 메시지를 보내는 것입니다.
  2. Objective-C에서 매개 변수는 메서드 호출이 끝날 때 모두 함께 사용되지 않습니다.

희망이 있습니다.

+0

Thx 대단히 설명을 위해 :) – Daniele

관련 문제