开发者

Memory leak problem NSAutoreleaseNoPool()

开发者 https://www.devze.com 2023-01-28 02:24 出处:网络
I am trying to create an immutable string. I am not initializing it with init, alloc or new but still the memory is leaking and its saying \"object 0x234b533 of Class NSCFString autoreleased with no p

I am trying to create an immutable string. I am not initializing it with init, alloc or new but still the memory is leaking and its saying "object 0x234b533 of Class NSCFString autoreleased with no pool in place - just leaking " here is what I am trying to do

NSMutableString *srn = [NSMutableString stringwithCString:devSID];

// devSID is *char

this leaves a leak. I have开发者_如何学Go tried this too

NSMutableString *srn = [NSMutableString stringwithCString:devSID length:sizeof(devSID)];

but this too doesn't work, however if I try initialize it with a simple string like this

NSMutableString *srn = @"this is my string";

it works, dont have any idea whats happening around. I am not using init or alloc but still there is a leak. I would be obliged if anyone could help me out to resolve this issue

Regards

Umair


The leak is caused by your autoreleasing an object without having an autorelease pool in place to take care of it. That usually happens when you're doing things apart from the main thread, via creating your own threads or just using the -performSelectorInBackground:withObject: convenience method. If you want to use the autorelease functionality (implied by the use of the NSMutableString class method here), you need to create an autorelease pool at the beginning of the block of code where you'll be using it and drain it at the end. In other words, something along these lines:

- (void)myBackgroundThing:(id)whatever
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSMutableString *srn = [NSMutableString stringwithCString:devSID];

    // etc...

    [pool release];
}


Try something like this

[[NSString stringWithCString:"Hello"] retain];

retain is a way to assess object ownership on objects that you didn't initially create, so this extends our rule of matching every alloc with a release or autorelease

Note: You have to balance your release count if you retain this object. If you will not release retained object then you will face memory leak problem.

0

精彩评论

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