ios - Objective C 中的动态缓冲区(带 ARC)

标签 ios objective-c memory-management automatic-ref-counting buffer

我正在尝试使用 NSString 对象的 - (void)getCharacters:(unichar *)buffer range:(NSRange)aRange 方法,但我有一个第一个参数的问题。 此 NSString 中的字符数不固定,因此我需要动态分配缓冲区(缓冲区的大小必须类似于 [my_string length] * sizeof(UniChar))。

我是 Objective-C 的新手,不知道该怎么做。 我可以像在 C 程序中一样使用 malloc(启用了 ARC)吗?

最佳答案

是的,您可以malloc()适当大小的缓冲区。你必须free()缓冲区 当不再使用它时,因为 ARC 不管理 malloced 内存。

或者,使用 UTF-16 编码创建一个 NSData 对象:

NSString *string = @"H€llö Wörld";
NSData *data = [string dataUsingEncoding:NSUTF16LittleEndianStringEncoding];
const unichar *charsPtr = [data bytes];

charsPtr 只要 data 存在就有效,即只要您保持对它的强引用。

关于ios - Objective C 中的动态缓冲区(带 ARC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23297653/

相关文章:

ios - 过滤NS数组,根据issynced值获取元素

ios - 基于内容的动态 UITableView 单元格高度

C++ 在不重新分配的情况下删除 vector 末尾的一部分

c - 指针类型转换如何在 C 中工作

objective-c - ld : library not found for -lz

ios - 在 UIImage 中渲染 MKPolyline

ios - 在我的例子中只有一个数组元素要排序

iphone - 告诉哪个 ViewController 推送了 DetailViewController

c++ - Objective-C++的缺点?

c++ - 释放包含 malloc 字符串的 malloc 结构