E. Rivera
E. Rivera

Reputation: 10938

Return Core Foundation object from a non-CF class method using ARC and iOS 5+ support

I have this method in a NSObject subclass:

- (CFStringRef)UTITypeForPath:(NSString *)path {
    NSString *extension = [path pathExtension];
    CFStringRef result = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL);
    return result;
  }

That generates this logic Analyzer warning:

Potential leak of an object stored into 'result'

The question is how to deal with it in a clean way:

Also I wonder if this method should return a retained object in the first place.

Upvotes: 1

Views: 709

Answers (1)

Martin R
Martin R

Reputation: 539725

Possible solutions:

Rename your method according to the naming conventions of the Objective-C Basic Memory Management Rules, e.g. start the method name with "copy":

- (CFStringRef)copyUTITypeForPath:(NSString *)path {
    NSString *extension = [path pathExtension];
    CFStringRef result = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL);
    return result;
}

Then the caller of the method is responsible for releasing the CFStringRef eventually.

Or change your method to return NSString * instead of CFStringRef:

- (NSString *)UTITypeForPath:(NSString *)path {
    NSString *extension = [path pathExtension];
    CFStringRef result = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL);
    return CFBridgingRelease(result);
}

In this case ARC will take care of releasing the NSString object.

Upvotes: 1

Related Questions