Rocky
Rocky

Reputation: 1287

iOS: CF object leaks

Here is my code under ARC:

- (NSString*)encodeURL:(NSString *)string
{
    NSString *anewString = (__bridge NSString *)(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding([self stringEncoding])));
    if (anewString) {
        return anewString;
    }
    return @"";
}

I analyzed this code and xcode gave me leak message.But I donnot know how to fix it. Please help!Thanks in advance!

Upvotes: 0

Views: 98

Answers (2)

nielsbot
nielsbot

Reputation: 16031

Instead of (__bridge NSString *)(...) use CFBridgingRelease( ... ), where "..." = your string creation.

Upvotes: 0

indragie
indragie

Reputation: 18132

CFURLCreateStringByAddingPercentEscapes() returns an owned object (retain count of +1). The __bridge cast bridges the CF object to Objective-C but does not transfer the ownership, so you create a memory leak because ARC does not know that the object is retained. Use __bridge_transfer instead of _bridge to transfer the ownership so that Objective-C ARC can take care it for you.

Upvotes: 2

Related Questions