将NSArray的CGPoints转换为NSData块

时间:2013-09-10 02:47:36

标签: ios objective-c nsarray nsdata cgpoint

我正在尝试将NSArray CGPoints转为NSData。我无法弄明白该怎么做。

根据http://www.raywenderlich.com/12910/how-to-make-a-simple-playing-card-game-with-multiplayer-and-bluetooth-part-3

     NSString *string = @"example"
     const char *cString = [string UTF8String];
     [self appendBytes:cString length:strlen(cString) + 1];

所以对于NSArray CGPoint,我无法弄清楚如何转换为NSData

2 个答案:

答案 0 :(得分:1)

一种方法是将您的点转换为C数组,然后从中生成NSData

NSMutableArray *array = [NSMutableArray array];
[array addObject:[NSValue valueWithCGPoint:pt1]];
[array addObject:[NSValue valueWithCGPoint:pt2]];
size_t total = sizeof(CGPoint)*array.count;
CGPoint *buf = malloc(total);
CGPoint *ptr = buf;
for (NSValue *v in array) {
    *ptr = v.CGPointValue;
}
NSData *res = [NSData initWithBytesNoCopy:buf length:total];

答案 1 :(得分:1)

你可以尝试:

    NSData * d = [NSData dataWithBytes:&tests[0] length:16] ;

然后:

    [d getBytes:&recovered[0] length:16] ;

如:

    CGPoint tests[] = {
        {10.0f, 20.0f}
    ,   {20.0f, 30.0f}
    } ;
    // 2 points each with 2 floats = 4 values of 4 bytes each = 16 bytes
    NSData * d = [NSData dataWithBytes:&tests[0] length:16] ;
    NSLog(@"NSData: %@", d) ;

    CGPoint recovered[2] ;
    [d getBytes:&recovered[0] length:16] ;
    NSLog(@"P1: %@, P2: %@", NSStringFromCGPoint(recovered[0]), NSStringFromCGPoint(recovered[1])) ;

这可能是最直接的方式。

打印:

2013-09-10 04:05:24.468 SoloTouch[55207:c07] NSData: <00002041 0000a041 0000a041 0000f041>
2013-09-10 04:05:43.566 SoloTouch[55207:c07] P1: {10, 20}, P2: {20, 30}