【问题标题】:How can I add CGPoint objects to an NSArray the easy way?如何以简单的方式将 CGPoint 对象添加到 NSArray?
【发布时间】:2010-10-28 07:52:48
【问题描述】:

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

【问题讨论】:

    标签: ios objective-c iphone cocoa-touch uikit


    【解决方案1】:

    随着UIKitApple 将 CGPoint 支持添加到NSValue,因此您可以这样做:

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

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

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

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

    【讨论】:

    • 对于标量类型,看看 NSNumber... 你会看到 numberWithBool: numberWithInteger: numberWithFloat:, numberWithUnsignedShort: 等构造函数。
    • 您也可以直接使用 NSValue:例如 [NSValue valueWithBytes: &someStructSockaddr objCType: @encode(struct sockaddr)]。
    【解决方案2】:

    我用这个:

    创建数组:

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

    获取第一个 CGPoint 对象:

    CGPoint myPoint = [myArray[0] CGPointValue];
    

    【讨论】:

      【解决方案3】:

      你也可以这样写:

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

      【讨论】:

        【解决方案4】:

        你看过CFMutableArray吗?这可能对你更有效。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-02-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多