1

谁能帮我找到以下函数中的内存泄漏

-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding :(NSString *)string {
    return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,  (CFStringRef)string,  NULL,  (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",  CFStringConvertNSStringEncodingToEncoding(encoding));
}

Instrument 在上述函数的每次调用中都会报告内存泄漏。

4

2 回答 2

4

CFURLCreateStringByAddingPercentEscapes在您拥有该对象时添加 +1 保留计数。所以你有责任释放那个对象。所以你需要拥有CFStringRef并在使用你的对象之后使用CFRelease来释放它。

-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding :(NSString *)string {
    CFStringRef stringRef = CFURLCreateStringByAddingPercentEscapes(NULL,  (CFStringRef)string,  NULL,  (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",  CFStringConvertNSStringEncodingToEncoding(encoding));
    NSString *returnString = (NSString*)stringRef;
    CFRelease(stringRef);
    return returnString;
}
于 2013-04-01T05:21:15.663 回答
1

解决方案取决于您是否使用 ARC。

使用 ARC,您可以转让所有权:

-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding :(NSString *)string {
    return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,  (CFStringRef)string,  NULL,  (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",  CFStringConvertNSStringEncodingToEncoding(encoding));
}

使用 MRC,您可以:

-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding :(NSString *)string {
    NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,  (CFStringRef)string,  NULL,  (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",  CFStringConvertNSStringEncodingToEncoding(encoding));

    return [result autorelease];
}
于 2013-04-01T05:19:21.210 回答