简体   繁体   中英

NSMutableString append data error


I have AsyncSocket like this.

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
NSString *message = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
[data getBytes:&tdata];
  if (tdata > 5) {

    if(bheader){
        if(!charS){
            if([message isEqualToString:@"S"]){
                CMSG = message;
                charS=YES;
            }
        }
        else{
            NSMutableString *tmp = [[NSMutableString alloc] initWithString:@""];
            [tmp appendString:CMSG];       <<<<< This is code error at loop 2, 
            [tmp appendString:message];     the first loop success but second is fail
            CMSG = tmp;
            [tmp release];
        }
    }
    else{  
        if (message){            
            cmessage = [[NSString alloc]initWithFormat:@"%@%@",cmessage,message]  ;
        }
        else
            NSLog(@"Error converting received data into UTF-8 String");

        cdata++;
        if(cdata==idata) {
            msgComplete=YES;
        }

    }

    if (msgComplete) {
        NSDictionary *userInfo = [NSDictionary dictionaryWithObject:cmessage forKey:kNotificationMessage];
        [notificationCenter postNotificationName:kNotification object:self userInfo:userInfo];
        cmessage=@"";
        CMSG=@"";
        msgComplete=NO;
        bheader=YES;
        cdata=0;
        charS=NO;
        [cmessage release];

    }
}

[sock readDataToLength:1 withTimeout:-1 tag:0];

}

This code fail at second loop at [tmp appendString:CMSG]; Thread 1: Program received signal "SIGABRT"
How fix this error ?
Thanks gurus,

CMSG is assigned to tmp but tmp is released right afterwards. CMSG needs to be retained throughout the loop.

CMSG = tmp;   //<< should be CMSG = [tmp retain];
[tmp release];

Now you have another potential problem. You are using a deprecated method here

[data getBytes:&tdata];
  if (tdata > 5) {

getBytes: was deprecated because of a potential buffer overrun and the result of getBytes is not appropriate to use for if(tdata > 5) . If you want to check the length of bytes get that that from the NSData object.

I see an error that may or may not be the ultimate problem here. In the final conditional statement, you have:

cmessage=@"";
...
[cmessage release];

I don't think you should be releasing that string. I don't actually know all of the ins and outs of NSString objects that are defined in that way (as opposed to stringWithFormat: or initWithString: ), but I don't think that you have ownership of that string object. You shouldn't have to release it.

Remove that release message and see if it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM