问题描述
我有大约 50 个描述类似路径"的 CGPoint 对象,我想将它们添加到 NSArray.这将是一个只返回给定索引对应的 CGPoint 的方法.我不想创建 50 个变量,例如 p1 = ...;p2 = ...,依此类推.有没有一种简单的方法可以让我在使用对象初始化 NSArray 时立即"定义这些点?
I have about 50 CGPoint objects that describe something like a "path", and I want to add them to an NSArray. It's going to be a method that will just return the corresponding CGPoint for an given index. I don't want to create 50 variables like p1 = ...; p2 = ..., and so on. Is there an easy way that would let me to define those points "instantly" when initializing the NSArray with objects?
推荐答案
通过 UIKit
Apple 为 NSValue
添加了对 CGPoint 的支持,所以你可以这样做:
With UIKit
Apple added support for CGPoint to NSValue
, so you can do:
NSArray *points = [NSArray arrayWithObjects:
[NSValue valueWithCGPoint:CGPointMake(5.5, 6.6)],
[NSValue valueWithCGPoint:CGPointMake(7.7, 8.8)],
nil];
列出与 CGPoint 一样多的 [NSValue] 实例,并以 nil 结束列表.此结构中的所有对象都是自动释放的.
List as many [NSValue] instances as you have CGPoint, and end the list in nil. All objects in this structure are auto-released.
另一方面,当您从数组中提取值时:
On the flip side, when you're pulling the values out of the array:
NSValue *val = [points objectAtIndex:0];
CGPoint p = [val CGPointValue];
这篇关于如何以简单的方式将 CGPoint 对象添加到 NSArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!