【问题标题】:Create an array of CGPoints by pairing values from two different NSArrays通过配对来自两个不同 NSArrays 的值来创建一个 CGPoints 数组
【发布时间】:2013-02-05 13:27:59
【问题描述】:

如何通过在objective-c中配对来自两个不同NSArrays的值来创建一个CGPoints数组?

假设我有一个数组“A”,其值:0, 1, 2, 3, 4
而且我还有一个数组“B”,其值为:21, 30, 33, 35, 31

我想用 CGPoint 值创建数组“AB”:(0,21), (1,30), (2,33), (3,35), (4,31)

感谢您的帮助。

【问题讨论】:

  • 数组 A 和数组 B 是 NSArray 的 NSNumber 对象吗?

标签: ios objective-c nsarray cgpoint


【解决方案1】:

其他人发布了制作 CGPoints NSArray 的帖子,但您要求制作 CGPoints 的 数组。这应该这样做:

NSArray* a = @[ @(0.), @(1.), @(2.), @(3.), @(4.) ];
NSArray* b = @[ @(21.), @(30.), @(33.), @(35.), @(31.) ];

const NSUInteger aCount = a.count, bCount = b.count, count = MAX(aCount, bCount);
CGPoint* points = (CGPoint*)calloc(count, sizeof(CGPoint));
for (NSUInteger i = 0; i < count; ++i)
{
    points[i] = CGPointMake(i < aCount ? [a[i] doubleValue] : 0 , i < bCount ? [b[i] doubleValue] : 0.0);
}

【讨论】:

    【解决方案2】:

    请注意,Objective-C 集合类只能保存对象,因此我假设您的 输入数字 保存在 NSNumber 对象中。这也意味着CGPointstructs 必须保存在组合数组中的NSValue 对象中:

    NSArray *array1 = ...;
    NSArray *array2 = ...;
    NSMutableArray *pointArray = [[NSMutableArray alloc] init];
    
    if ([array1 count] == [array2 count])
    {
        NSUInteger count = [array1 count], i;
        for (i = 0; i < count; i++)
        {
            NSNumber *num1 = [array1 objectAtIndex:i];
            NSNumber *num2 = [array2 objectAtIndex:i];
            CGPoint point = CGPointMake([num1 floatValue], [num2 floatValue]);
            [pointArray addObject:[NSValue valueWithCGPoint:point]];
        } 
    }
    else
    {
        NSLog(@"Array count mis-matched");
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      相关资源
      最近更新 更多