复制是否分配所需的内存?

时间:2010-10-19 07:55:13

标签: objective-c copy alloc

以下是Apple iPhone SDK项目的示例:

@interface EADSessionController : NSObject <EAAccessoryDelegate, NSStreamDelegate> {
    EAAccessory *_accessory;
    EASession *_session;
    NSString *_protocolString;

    NSMutableData *_writeData;
    NSMutableData *_readData;
}

...

// initialize the accessory with the protocolString
- (void)setupControllerForAccessory:(EAAccessory *)accessory withProtocolString:(NSString *)protocolString
{
    [_accessory release];
    _accessory = [accessory retain];
    [_protocolString release];
    _protocolString = [protocolString copy];
}

我的理解是“copy”还将分配复制作为参数传递的protocolString对象所需的内存,因此在复制之前不需要分配(alloc)。

我是对的吗?

此致 Apple92

1 个答案:

答案 0 :(得分:0)

正确。副本的保留计数(至少)为1,并且您有责任最终释放它。 (见Object Ownership Policy。)