如何为@property变量分配空间

时间:2013-07-08 05:55:39

标签: ios objective-c xcode variables

我仍然是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];
}

如果有人可以告诉我变量声明的@propertyimplementation空间之间的真正区别,这会阻止我做出这样的其他错误。 非常感谢。

2 个答案:

答案 0 :(得分:2)

如果您需要将其声明为unsigned char*,则malloc / calloc / realloc / free是您的朋友。

实际上,制作ivar NSMutableData并使用-appendBytes:length:之类的API应该是必要的。

答案 1 :(得分:1)

使用NSMutableData:

@property (strong) NSMutableData *recievedData;

它为任意内存提供了一个很好的包装器,它的内容和长度可以随时改变 - 最重要的是它完全符合objective-c运行时和内存管理。

只需创建一个空的(0长度)数据对象,如下所示:

self.receivedData = [[NSMutableData alloc] init];

然后你可以随时做到:

[self.recivedData appendBytes:bytes length:length];

或者:

[self.recievedBytes appendData:anotherNSDataObj];

从那里你可以用getBytes:方法阅读它。

通过声明较低级别的实例变量,还有其他方法可以做到这一点,但@property是现代方法。较旧的实例变量样式能够满足您的要求,但我们正在逐渐远离它们,很快就会被弃用。