【发布时间】:2015-05-28 09:50:10
【问题描述】:
我遇到了一些优化代码的崩溃。我要做的是在前一个点和下一个点足够接近时从输入数组中删除一些点。该方法几乎适用于所有情况,但会因某些特定数据而崩溃。
输入数据崩溃的例子:
Value of coords : (51.55188, -0.17591), (51.55208, -0.17516), (51.55231, -0.17444)
Value of altitudes : 10000, 10000, 10000
Value of count : 3
如果我跳过优化代码并直接使用输入值,那么一切正常。如果我只是 memcpy 临时数组中的输入值,它也可以正常工作。
在使用此方法并发布输入数据后,我得到了 EXC_BAD_ACCESS EXC_I386_GPFLT。崩溃不会直接发生在此方法中,而是在我使用在方法末尾创建的对象之后。我已经为僵尸尝试过 NSZombie 和 Profiling。几乎所有数据都可以正常工作,但使用这个特定的输入数据会导致 100% 崩溃(至少它对我来说更容易调试!)。
我的方法的代码:
+ (instancetype) optimizedPolylineWithCoordinates:(CLLocationCoordinate2D*) coords altitudes:(RLMKAltitude*) altitudes count:(NSUInteger) count
{
CGFloat minimumDistanceBetweenPoints = [self minimumOptimizedDistanceBetweenPoints];
CLLocationCoordinate2D* tempCoords = malloc(sizeof(CLLocationCoordinate2D) * count);
RLMKAltitude* tempAltitudes = malloc(sizeof(RLMKAltitude) * count);
NSUInteger tempCoordsCount = 0;
// Always keep first point
tempCoords[0] = coords[0];
tempAltitudes[0] = altitudes[0];
++tempCoordsCount;
for (NSUInteger i = 1; i < (count - 1); i++)
{
MKMapPoint prevPoint = MKMapPointForCoordinate(coords[i - 1]);
MKMapPoint nextPoint = MKMapPointForCoordinate(coords[i + 1]);
// Get the distance between the next point and the previous point.
CLLocationDistance distance = MKMetersBetweenMapPoints(nextPoint, prevPoint);
// Keep the current point if the distance is greater than the minimum
if (distance > minimumDistanceBetweenPoints)
{
tempCoords[tempCoordsCount] = coords[i];
tempAltitudes[tempCoordsCount] = altitudes[i];
++tempCoordsCount;
}
}
// Always keep last point
tempCoords[tempCoordsCount] = coords[(count - 1)];
tempAltitudes[tempCoordsCount] = altitudes[(count - 1)];
++tempCoordsCount;
RLMKMapWay* object = [self polylineWithCoordinates:tempCoords altitudes:tempAltitudes count:tempCoordsCount];
free(tempCoords);
free(tempAltitudes);
return object;
}
请注意,使用临时数据调用的 polylineWithCoordinates 方法负责复制所有数据,因此问题可能与调用后的 free 无关(我已经尝试评论这两行并且崩溃仍然发生)
【问题讨论】:
-
崩溃发生在哪一行?
-
我有点困惑...
CLLocationCoordinate2D不是结构吗?为什么要引用它的地址空间 (1) 和 (2) 在不使用 .location或.longitude的情况下如何访问它?此外,获取对象的大小需要stackoverflow.com/questions/761969/… -
作为输入的 CLLocationCoordinate2D 指针是一个 C 风格的 CLLocationCoordinate2D 数组。此外,使用 sizeof 是正确的,因为 CLLocationCoordinate2D 的大小在编译时是已知的。
标签: ios objective-c malloc