ios 如何以简单的方式将 CGPoint 对象添加到 NSArray?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/899600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:56:54  来源:igfitidea点击:

How can I add CGPoint objects to an NSArray the easy way?

iosobjective-ciphonecocoa-touchuikit

提问by Thanks

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?

我有大约 50 个 CGPoint 对象描述了“路径”之类的东西,我想将它们添加到 NSArray 中。这将是一个只返回给定索引对应的 CGPoint 的方法。我不想创建 50 个变量,比如 p1 = ...; p2 = ...,依此类推。有没有一种简单的方法可以让我在用对象初始化 NSArray 时“立即”定义这些点?

回答by Jarret Hardie

With UIKitApple added support for CGPoint to NSValue, so you can do:

随着UIKitApple 添加对 CGPoint 的支持NSValue,您可以执行以下操作:

NSArray *points = [NSArray arrayWithObjects:
                     [NSValue valueWithCGPoint:CGPointMake(5.5, 6.6)],
                     [NSValue valueWithCGPoint:CGPointMake(7.7, 8.8)],
                     nil];

List as many [NSValue] instances as you have CGPoint, and end the list in nil. All objects in this structure are auto-released.

列出与 CGPoint 一样多的 [NSValue] 实例,并以 nil 结束列表。此结构中的所有对象都是自动释放的。

On the flip side, when you're pulling the values out of the array:

另一方面,当您从数组中提取值时:

NSValue *val = [points objectAtIndex:0];
CGPoint p = [val CGPointValue];

回答by Tibidabo

I use this:

我用这个:

Create array:

创建数组:

NSArray *myArray = @[[NSValue valueWithCGPoint:CGPointMake(30.0, 150.0)],[NSValue valueWithCGPoint:CGPointMake(41.67, 145.19)]];

Get 1st CGPoint object:

获取第一个 CGPoint 对象:

CGPoint myPoint = [myArray[0] CGPointValue];

回答by GilesDMiddleton

You can also write this in a minimal form of:

您还可以以最小形式编写此内容:

CGPoint myArray[] = { CGPointMake(5.5, 6.6), CGPointMake(7.7, 8.8) };

CGPoint p2 = myArray[1];

回答by Ramin

Have you taken a look at CFMutableArray? That might work better for you.

你看了CFMutableArray吗?那可能更适合你。