如何初始化 NSData 以存储 MAX_SIZE_BUFFER 字节?

发布于 2024-09-27 19:58:30 字数 959 浏览 0 评论 0原文

我刚刚意识到我花了 30 分钟在 Xcode NSData 类参考中搜索如何在 objc 中执行此操作(抱歉,我用 C 解释了这一点,因为这是唯一没有考虑太多的语言):

#define MAX_SIZE_BUFFER 500
byte *ptr;
ptr = malloc(MAX_SIZE_BUFFER * sizeof(byte));
memset(ptr, 0, MAX_SIZE_BUFFER);

我开始像这样编码,但从未找到如何以聪明的方式初始化 MAX_SIZE_BUFFER 并将所有字节设置为 0:

#define MAX_SIZE_BUFFER 500
NSData *ptr
ptr = [[[NSData] alloc] init]; // impossible to specify MAX_SIZE_BUFFER in the allocation.

因此我告诉自己,让我们使用类似的类方法:

+ data
+ dataWithBytes:length:
+ dataWithBytesNoCopy:length:
+ dataWithBytesNoCopy:length:freeWhenDone:
+ dataWithContentsOfFile:
+ dataWithContentsOfFile:options:error:
+ dataWithContentsOfMappedFile:
+ dataWithContentsOfURL:
+ dataWithContentsOfURL:options:error:
+ dataWithData:

但它们都不能执行分配和空白初始化。

例如: + dataWithBytes:length: 要求创建一个备用 C 缓冲区并将其作为该方法的参数。

我应该认为自己是一个白痴还是一个 objc 糟糕的程序员?

说真的,你有一个聪明而简单的方法吗?

苹果92

I have just realized I lost 30 minutes searching in Xcode NSData Class reference how to do this in objc (sorry I explain this in C as this in the only language which comes without thinking too much):

#define MAX_SIZE_BUFFER 500
byte *ptr;
ptr = malloc(MAX_SIZE_BUFFER * sizeof(byte));
memset(ptr, 0, MAX_SIZE_BUFFER);

I started to code like this but never found out how to init MAX_SIZE_BUFFER and set all bytes to 0 in a smart way:

#define MAX_SIZE_BUFFER 500
NSData *ptr
ptr = [[[NSData] alloc] init]; // impossible to specify MAX_SIZE_BUFFER in the allocation.

Thus I told myself, let's use a class method like:

+ data
+ dataWithBytes:length:
+ dataWithBytesNoCopy:length:
+ dataWithBytesNoCopy:length:freeWhenDone:
+ dataWithContentsOfFile:
+ dataWithContentsOfFile:options:error:
+ dataWithContentsOfMappedFile:
+ dataWithContentsOfURL:
+ dataWithContentsOfURL:options:error:
+ dataWithData:

but none of them enables to do the alloc and blank init symply.

For example: + dataWithBytes:length: requires that an alternate C buffer be created and given as a parameter to the method.

Should I consider myself like an idiot or like an objc bad programmer ?

Seriously, do you have a smart and simple method ?

Apple92

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

慕烟庭风 2024-10-04 19:58:30

NSData 是不可变的,因此这就是为什么所有初始化程序都需要缓冲区内容的原因。你想要的是 NSMutableData 的 initWithLength:

http:// developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSMutableData_Class/Reference/NSMutableData.html

NSData is immutable, so that's why all the initializers require the contents of the buffer. What you want is NSMutableData's initWithLength:

http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSMutableData_Class/Reference/NSMutableData.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文