开发者

Use NSMutableData but appendData failed

开发者 https://www.devze.com 2023-03-17 09:59 出处:网络
When I init NSMutableData with 100 length,it append data failed. self.receiveData = [[NSMutableData alloc] initWithLength:100];

When I init NSMutableData with 100 length,it append data failed.

self.receiveData = [[NSMutableData alloc] initWithLength:100];
if (nil == self.receiveData) {
    MYLOG;
    return NO;
}
- (void)connection:(NSURLConnection *)aConn didReceiveData:(NSData *)data {
    [self.receiveData appendData:data];
    NSString *string = [[NSString alloc] initWithData:self.receiveData encoding:NSUTF8StringEncoding];
    NSLog(@"%@",string);//there can't log any string
    MYLOG;
    [string release];
}

But when I init with 0 length,it can append well

self.receiveData = [[NSMutableData alloc] initWithLength:开发者_如何学Python0];
if (nil == self.receiveData) {
    MYLOG;
    return NO;
}

I'm new to Objective-C, can you help me with that ?


There's a difference between initWithLength: and initWithCapacity:. initWithLength: actually gives you that many bytes of 0s at the beginning of the data, while initWithCapacity: is just a hint for storage purposes. If you try to make a string out of data with 0s at the beginning, it will be an empty string.


use initWithCapacity: and here you are leaking with memory leak, if you have declared receiveData as retain in your property.

self.receiveData = [[[NSMutableData alloc] initWithCapacity:0] autorelease];

OR

 NSMutableData * myData =  [[NSMutableData alloc] initWithCapacity:0];
   self.receiveData = myData ;
   [myData release];
    myData  = nil ;


Try -initWithCapacity: or +dataWithCapacity: instead. -initWithLength: creates a data object containing the number of bytes that you specify. So, when you append data to your mutable data object, you get an object containing 100 bytes of zero, followed by whatever data you appended. It's likely that NSString looks at that first zero byte and returns an empty string.


I Just did it this way:

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

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.globalData appendData:data];
    float progress = (float)[self.globalData length] / self.downloadSize;
    self.threadProgressView.progress = progress;
}

And it works pretty well, give it a try...

0

精彩评论

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