Correct way to use __ attribute __ ((NSObject)) with ARC?

I'm just using CFNumber as an example, so it can be any type that doesn't have the free Fundation part!

I just write test code like this:

typedef  __attribute__((NSObject)) CFNumberRef MYNumberRef;

int main(int argc, const char * argv[])

    @autoreleasepool {
    MYNumberRef ptr = NULL;
    double myDouble = 10.1;
    ptr = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &myDouble);
    CFIndex count = CFGetRetainCount(ptr);
    return 0;


It's very strange that the counter is 2. But if I use CFNumberRef

, the counter is 1. It seems arc

to ignore the convention CFType

, it's just the retain

return value.

So if I use a property __attribute__((NSObject))

to declare CFType

. This post said you shouldn't have to explicitly nil them out in dealloc.

But if I use like this:

   @property (strong, nonatomic, readwrite) __attribute__((NSObject)) CFNumberRef number;



   self.number = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &myDouble);


No memory leak if I don't release it in the method dealloc

? Maybe I should use it like this:

  CFNumbeRef ref =  CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &myDouble);
  self.number = ref;


Does Apple say something about this?


source to share

1 answer

Do not do that.

Apple has a lot to say about this in the Clang documentation :

The use of __attribute__((NSObject))

typedefs is not recommended. If its absolutely necessary to use this attribute, be very explicit in your use of the typedef and do not assume that it will be preserved by language features such as __typeof

replacing C ++ template arguments.


meaningless . Worse than pointless because you think it might mean something.



All Articles