如何初始化 NSData 以存储 MAX_SIZE_BUFFER 字节?
我刚刚意识到我花了 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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