NSMutableString附加数据错误

时间:2011-05-20 13:00:44

标签: iphone nsstring


我有这样的AsyncSocket。

- (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];

}

此代码在[tmp appendString:CMSG];的第二个循环失败。线程1:编程接收信号“SIGABRT”
如何修复此错误?
谢谢大师,

2 个答案:

答案 0 :(得分:0)

CMSG被分配给tmp,但tmp随后被释放。 CMSG需要在整个循环中保留。

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

现在你有另一个潜在的问题。您在这里使用了弃用的方法

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

getBytes:由于潜在的缓冲区溢出而被弃用,并且getBytes的结果不适合用于if(tdata > 5)。如果要检查字节长度,请从NSData对象中获取该字节长度。

答案 1 :(得分:0)

我在这里看到的错误可能是也可能不是最终的问题。在最后的条件声明中,您有:

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

我认为你不应该释放那个字符串。我实际上并不知道以这种方式定义的NSString个对象的所有细节(与stringWithFormat:initWithString:相对),但我不认为你拥有该字符串对象的所有权。你不应该发布它。

删除release消息并查看是否有帮助。