简体   繁体   English

将NSArray的CGPoints转换为NSData块

[英]Turn NSArray of CGPoints into a block of NSData

I am trying to turn a NSArray of CGPoints to NSData . 我试图将NSArrayCGPointsNSData I can't figure out how to do it. 我无法弄清楚该怎么做。

According to http://www.raywenderlich.com/12910/how-to-make-a-simple-playing-card-game-with-multiplayer-and-bluetooth-part-3 根据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];

so with the NSArray of CGPoint s, I can't figure out how I can convert to NSData ? 所以使用CGPointNSArray ,我无法弄清楚如何转换为NSData

One way is to turn your points into a C array, then make an NSData out of it: 一种方法是将您的点转换为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];

You could try: 你可以尝试:

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

And then: 接着:

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

As in: 如:

    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])) ;

This is probably the most direct way. 这可能是最直接的方式。

This prints: 这打印:

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM