我的目的是比较 CGPoints
或 CGPoint
值(因为该应用程序也适用于 Mac OS NSPoints
或 NSPoint
值)的几个移动对象来检测对象是否具有相同的位置。
我的第一个解决方案是快速枚举这些对象的数组并将所有 CGPoints
存储到一个数组,然后再次快速枚举对象数组以检查位置是否相同其他对象:
// STEP 1: Collect all Positions
NSMutableArray *allPositions = [NSMutableArray arrayWithCapacity:self.allObjects.count];
for (Object *myObject in self.allObjects) {
CGPoint myObjectPosition = ...;
[allPositions addObject:myObjectPosition]; // Problem here
}
// STEP 2: Check for Overlapping
for (Object *myObject in self.allObjects) {
CGPoint myObjectPosition = ...;
if ([allPositions containsObject:myObjectPosition] {
// Overlapping
}
}
问题是将点添加到 allPositions
数组。因此可以使用 NSValue
:
[NSValue valueWithCGPoint:point];
但这只在 iOS 下有效,对于 Mac OS 必须使用 valueWithPoint
和 NSPoint
。
我可以保存或保存字典中的 x
和 y
值并将它们存储到 allPositions
数组吗?或者有没有 2x 快速枚举的更好解决方案? self.allObjects
中大约有100个对象...
最佳答案
CGPoint 和 NSPoint 是相同的结构。如果他们有不同的名字并不重要,他们都持有两个CGFloat。它们具有相同的尺寸和相同的对齐方式,因此可以互换使用。所以在您的情况下 valueWithPoint: 适合。
编辑
关于你问的第二件事,这应该用宏来完成:
#if TARGET_OS_IPHONE
value= [NSValue valueWithCGPoint: point];
#else
value= [NSValue valueWithPoint: point];
#endif
回到正题:
#if TARGET_OS_IPHONE
point= value.CGPointValue;
#else
point= value.pointValue;
#endif
http://sealiesoftware.com/blog/archive/2010/8/16/TargetConditionalsh.html
关于iOS/Mac 操作系统 : Saving and comparing CGPoints/NSPoints in Arrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17168052/