开发者

allocating error NSString?

开发者_运维百科

i used the code below :

for (int i=1; i<=3;i++){
    NSString *theString = [[NSString alloc] initWithFormat:@"%i",imageValue];
   theString = [theString stringByAppendingFormat:@"%i.jpg",i];
    [img addObject:theString];
    NSLog(@"the string %@:",theString); //01.jpg ,02.jpg and 03.jpg
    [theString release];
}

but i got this error 3 times why ?

Error:

myapp(15467,0xacdaa2c0) malloc: *** error for object 0x4eb1ca0: pointer being freed was not allocated


stringByAppendingFormat returns a new string, with is autoreleased. So that means you are releasing an autoreleased object, which is why you're getting the error, and you're leaking the string allocated on the first line. I would suggest to change that first line to

NSString* theString = [NSString stringWithFormat:@"%i", imageValue];

and then delete the release completely.


try

NSString *theString = [[NSString alloc] initWithFormat:@"%i%i.jpg",imageValue,i];

and remove

theString = [theString stringByAppendingFormat:@"%i.jpg",i];


In the first string inside the loop you declare the pointer theString and allocate an object:

NSString *theString = [[NSString alloc] initWithFormat:@"%i",imageValue];

In the second line you redirect the pointer theString to the new allocated autoreleased string [theString stringByAppendingFormat:@"%i.jpg",i];, so the previously allocated object is lost. This is a memory leak.

Finally, you release the autoreleased sting [theString release];, which will deallocate the object and crash the application when the autorelease loop will try to release the object again.

Solotion: read the edsko's answer.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜