我对 Objective-C 还是个新手,我需要一些关于变量声明的知识。
我的程序的重点是读取在多个 NSData
部分中传递的消息。每当程序收到 NSData
时,它会将其作为无符号字符添加到已经部分完成的消息中。这意味着消息缓冲区必须定义为 viewController
的属性:
@property unsigned char* receiveBuf;
@property int bufSize;
那时程序有一个名为 data 的 NSData
对象,并像这样对待它:
int len = [data length];
unsigned char* tempBytebuf = (unsigned char*)[data bytes];
for(int i = 0; i < len; i++){ //read all bytes
if (tempBytebuf[i] == 0x7E) { //this char means start of package
_bufSize = 0;
}
else if (tempBytebuf[i] == 0x7D) { //this char means end of package
[self readMsgByte:_receiveBuf :_bufSize];
}
else { //any other char is to be put in the message
_receiveBuf[_bufSize++] = tempBytebuf[i]; //Error happens here
}
}
如果我继续这样做,将导致错误 EXC_BAD_ACCESS。 如果我可以告诉程序为缓冲区保留空间,它就会解决问题:
@property unsigned char receiveBuf[256];
但似乎我不能用@properties
来做到这一点。
例如,有没有办法在 ViewDidLoad()
或其他地方分配该空间?
感谢您的支持!
编辑 1:
看来我刚刚在我以前的一些代码中找到了解决方案,我应该在实现中声明我的 char 表。
@implementation ViewController
{
unsigned char msgBuf[256];
}
不过,如果有人能告诉我变量声明的 @property
和 implementation
空间之间的真正区别,那将防止我犯其他类似的错误。
非常感谢。
最佳答案
如果您需要将其声明为 unsigned char*
,那么 malloc/calloc/realloc/free 是您的 friend 。
实际上,制作那个 ivar NSMutableData
并使用像 -appendBytes:length:
这样的 API 应该是所有必要的。
关于ios - 如何为@property 变量分配空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17519964/