3

I am trying to turn a NSArray of CGPoints to NSData. 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

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

so with the NSArray of CGPoints, I can't figure out how I can convert to NSData?

Extra Savoir-Faire
  • 6,026
  • 4
  • 29
  • 47
fftoolbar
  • 175
  • 1
  • 1
  • 11
  • I'd like to see the code where you made an NSArray of CGPoints. Presumably they are wrapped, like in NSValues? – danh Sep 10 '13 at 04:16

2 Answers2

1

One way is to turn your points into a C array, then make an NSData out of it:

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];
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

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}
verec
  • 5,224
  • 5
  • 33
  • 40