Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage collection of Core Foundation objects

Running the static analyzer on this piece of code:

- (id) readForeignPref
{
 CFPropertyListRef matchStyle = CFPreferencesCopyAppValue(CFSTR("PBXFindMatchStyle"), CFSTR("com.apple.Xcode"));
 return [(id)matchStyle autorelease];
}

yields the following warning:

Call to function 'CFPreferencesCopyAppValue' returns a Core Foundation object with a +1 retain count (owning reference). Core Foundation objects are not automatically garbage collected.

Is this a warning I should fix with somethin ugly like that:

- (id) readForeignPref
{
 CFPropertyListRef matchStyle = CFPreferencesCopyAppValue(CFSTR("PBXFindMatchStyle"), CFSTR("com.apple.Xcode"));
 id nsMatchStyle = [(id)matchStyle copy];
 if (matchStyle) {
  CFRelease(matchStyle);
 }
 return [nsMatchStyle autorelease];
}

or is this just a false positive, given that the copied object is toll-free bridged?

like image 235
0xced Avatar asked Feb 28 '23 08:02

0xced


1 Answers

Try this:

- (id) readForeignPref
{
      CFPropertyListRef matchStyle = CFPreferencesCopyAppValue(CFSTR("PBXFindMatchStyle"), CFSTR("com.apple.Xcode"));
      return [(id)CFMakeCollectable(matchStyle) autorelease];
}

Without the CFMakeCollectable, this will leak in GC, because a CFRetain is different than an ObjC -retain. A CFRetain disables garbage collection of that object, and needs CFMakeCollectable to enable it.

like image 121
kperryua Avatar answered Mar 12 '23 09:03

kperryua