[英]Turn NSArray of CGPoints into a block of NSData
我試圖將NSArray
的CGPoints
為NSData
。 我無法弄清楚該怎么做。
NSString *string = @"example"
const char *cString = [string UTF8String];
[self appendBytes:cString length:strlen(cString) + 1];
所以使用CGPoint
的NSArray
,我無法弄清楚如何轉換為NSData
?
一種方法是將您的點轉換為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];
你可以嘗試:
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}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.