开发者

Understanding release with NSMutableData returning from a Function

Currently I'm working on enha开发者_运维知识库ncing a project that has been developed by an external company for us. I'm still in the learning phases of IOS development, so want to make sure that I do things right at the beginning rather than hurt at the end of the project. I'm running Analyze on the project and getting a "Potential leak of an object allocated on line 166 and stored into 'commandToSend'" from the following block of code.

-(NSData*)GetBusinessCodeBase64:(NSString*)strBusiCode{
    NSArray *tmp_arr = [strBusiCode componentsSeparatedByString:@"-"];
    NSMutableData *commandToSend= [[NSMutableData alloc] init];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < [tmp_arr count]; i++) {
        byte_chars[0] = [[tmp_arr objectAtIndex:i] characterAtIndex:0];
        byte_chars[1] = [[tmp_arr objectAtIndex:i] characterAtIndex:1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [commandToSend appendBytes:&whole_byte length:1]; 
    }
    //NSData *result = [NSData dataWithData:commandToSend];
    //[commandToSend release];
    //return result;
    return commandToSend;
}

My investigating of this is that the call to this function wants an NSData* to be returned. So I looked at doing

NSData *result = [NSData dataWithData:commandToSend];
[commandToSend release];
return result;

instead of the direct return of commandToSend.

Is this the correct way of returning NSMutableData objects without leaking or is there some other way that I should be doing this.


Your solution works if you wish to ensure that an immutable NSData is returned. Alternatively, you could change the definition for commandToSend to:

NSMutableData *commandToSend = [NSMutableData data];
...
return commandToSend;

I would prefer this solution, it's less code and perfectly okay as NSMutableData is a subclass of NSData. It's really up to you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜