2010-04-05 51 views
15

經過一番搜索,我得到了以下解決方案: reference在NSMutableArray中存儲CLLocationCoordinates2D

CLLocationCoordinate2D* new_coordinate = malloc(sizeof(CLLocationCoordinate2D)); 
new_coordinate->latitude = latitude; 
new_coordinate->longitude = longitude; 
[points addObject:[NSData dataWithBytes:(void *)new_coordinate 
length:sizeof(CLLocationCoordinate2D)]]; 
free(new_coordinate); 

,並獲得它:

CLLocationCoordinate2D* c = (CLLocationCoordinate2D*) [[points objectAtIndex:0] bytes]; 

然而,有人聲稱有內存泄漏嗎?任何人都可以建議我在哪裏泄漏以及如何修復它。此外,有沒有更好的方式存儲在NSMutableArray中的CLLocationCoordinate2D列表?由於我是Objective C的新手,請給出示例代碼。

回答

6

沒有泄漏,只是堆內存的浪費。

你可以只使用

CLLocationCoordinate2D new_coordinate; 
new_coordinate.latitude = latitude; 
new_coordinate.longitude = longitude; 
[points addObject:[NSData dataWithBytes:&new_coordinate length:sizeof(new_coordinate)]]; 
70

這裏的另一種方式,使用內置型NSValue這是出於這樣的目的製作:

CLLocationCoordinate2D new_coordinate = { latitude, longitude }; 
[points addObject:[NSValue valueWithBytes:&new_coordinate objCType:@encode(CLLocationCoordinate2D)]]; 

檢索值使用下面的代碼:

CLLocationCoordinate2D old_coordinate; 
[[points objectAtIndex:0] getValue:&old_coordinate]; 
+1

NSValue是一個更好的選擇,因爲這是專門針對這一點,你也應該擺脫結構 – 2011-03-09 07:56:08

+0

我創建了一個對象,其中包含兩個用於保存經度和緯度的雙重屬性... 因爲我必須添加NSCoding合規性。 它沒有成功使用這個建議,因爲雖然堅持它認爲它是結構,並且它不能編碼結構。 – LolaRun 2013-03-04 09:52:29

+0

@LolaRun在SO後續問題上不滿意。您應該將其作爲單獨的問題發佈。 – 2013-03-04 11:46:53

50

從iOS 6開始,有NSValueMapKitGeometryExtensionsNSValue

CLLocationCoordinate2D new_coordinate = CLLocationCoordinate2DMake(latitude, longitude); 
[points addObject:[NSValue valueWithMKCoordinate:new_coordinate]]; 

,並檢索值:

CLLocationCoordinate2D coordinate = [[points objectAtIndex:0] MKCoordinateValue]; 

NSValueMapKitGeometryExtensions需要MapKit.framework
CLLocationCoordinate2DMake()需要CoreLocation.framework

+0

需要mapkit框架才能使用valueWithMKCoordinate – chings228 2013-12-07 07:41:13

+0

這應該是ACCEPTED ANSWER – Jaro 2016-05-18 21:48:47