gpt4 book ai didi

cocoa - NSData 和嵌入式指针澄清

转载 作者:行者123 更新时间:2023-12-03 16:51:20 28 4
gpt4 key购买 nike

有关 NSData 的 Apple 文档说

NSData and its mutable subclass NSMutableData provide data objects, object-oriented wrappers for byte buffers. Data objects let simple allocated buffers (that is, data with no embedded pointers) take on the behavior of Foundation objects.

“嵌入指针”是什么意思?我的理解是,一旦你将字节放入其中,它就不知道它是什么,除非你在应用程序级别对其进行解码。有人知道他们在说什么吗?

最佳答案

NSData 的目的是提供一种方法,当不再需要分配的数据缓冲区时,即当 NSData 的引用计数变为 0 时,清理该数据缓冲区。在常见情况下,数据是通过 malloc 分配的,而 NSData 使用相应地调用 free 来释放数据。这对字节数据的性质施加了限制。它必须是普通旧数据。如果数据是一个结构体,其中包含一个字段,该字段指向用 malloc(嵌入式指针)分配的另一个内存区域,则该嵌入式指针永远不会被 NSData 对象释放,从而导致内存泄漏。例如:

typedef struct Point {
CGFloat x,
CGFloat y
} Point;

typedef struct LineSegment {
Point* start;
Point* end;
} LineSegment;

// point does not contain any embedded pointers (i.e., it is Plain Old Data)
Point* point = malloc(sizeof(Point));
// pointData will call free on point to deallocate the memory allocated by malloc
NSData* pointData = [NSData dataWithBytesNoCopy:point length:sizeof(Point)];

Point* start = malloc(sizeof(Point));
Point* end = malloc(sizeof(Point));

// line contains two embedded pointers to start and end. Calling free on line
// without calling free on start and end will leak start and end
LineSegment* line = malloc(sizeof(LineSegment));
line->start = start;
line->end = end;

// start and end will be leaked!
NSData* lineData = [NSData dataWithBytesNoCopy:&line length:sizeof(LineSegment)];

// Try this instead. Line is now Plain Old Data
typedef struct Line {
Point start;
Point end;
} Line;

// anotherLine does not contain any embedded pointers and can safely be used with
// NSData. A single call to free will deallocate all memory allocated for anotherLine
// with malloc
Line* anotherLine = malloc(sizeof(Line));

NSData* anotherLineData = [NSData dataWithBytesNoCopy:&anotherLine
length:sizeof(Line)];

关于cocoa - NSData 和嵌入式指针澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12343794/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com