2013-02-20 73 views
3

如何通過在objective-c中配對來自兩個不同NSArrays的值來創建一個CGPoint數組?通過配對來自兩個不同NSArrays的值創建一個CGPoint數組

可以說,我有一個數組「A」的價值觀:0, 1, 2, 3, 4
而且我也有一個陣列「B」的價值觀:21, 30, 33, 35, 31

我想創建陣列「AB」與CGPoint值:(0,21), (1,30), (2,33), (3,35), (4,31)

感謝您的幫助。

+0

數組A和數組B是NSArray的NSNumber對象? – jamapag 2013-02-20 14:02:49

回答

5

請注意,Objective-C集合類只能保存對象,所以我假設您的輸入數字保存在NSNumber對象中。這也意味着,CGPointstruct小號必須在合併數組中的一個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"); 
} 
2

別人張貼在製造的NSArray CGPoints的,但你問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); 
} 
相關問題