문제

How to create an array of CGPoints by pairing values from two different NSArrays in objective-c?

Lets say I have an Array "A" with the values: 0, 1, 2, 3, 4
And I also have an Array "B" with the values: 21, 30, 33, 35, 31

I would like to create Array "AB" with CGPoint values: (0,21), (1,30), (2,33), (3,35), (4,31)

Thanks for your help.

도움이 되었습니까?

해결책

Note that Objective-C collection classes can only hold objects, so I have assumed your input numbers are held in NSNumber objects. This also means that the CGPoint structs must be held in a NSValue object in the combined array:

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");
}

다른 팁

Someone else posted on making an NSArray of CGPoints, but you asked for an array of CGPoints. This ought to do that:

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);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top