将CGPoint的NSArray转换为NSData块

3

我想看一下你创建一个CGPoint的NSArray的代码。它们应该被包装在NSValue中,对吗? - danh
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];

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}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接