Question

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:

  • I can't use CFAutorelease because it's iOS 7+ only.
  • Can't use Apple Core Foundation naming conventions (Create/Get rules) because it is an Objective-C method and not a C function (in contrast with this related question).

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top