3

我正在尝试将a转为NSArray。我不知道该怎么做。CGPointsNSData

根据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];

所以对于NSArrays CGPoint,我不知道如何转换为 s NSData

4

2 回答 2

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];
于 2013-09-10T02:56:35.843 回答
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}
于 2013-09-10T03:09:54.030 回答