在ARC中使用__attribute __((NSObject))的正确方法?

时间:2014-09-28 23:49:48

标签: ios objective-c automatic-ref-counting core-foundation

我只是以CFNumber为例,所以它可以是任何类型都没有Fundation免费部分!

我只是写了一些像这样的测试代码:

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;
}

计数为2是非常奇怪的。但如果我使用CFNumberRef,则计数为1. arc似乎不考虑CFType名称约定,它只是retain的返回值。

因此,如果我使用__attribute__((NSObject))来声明CFType属性。 This postyou shouldn't have to explicitly nil them out in dealloc.但如果我这样使用:

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

然后:

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

如果我不在dealloc方法中释放它,则没有内存泄漏?也许我应该像这样使用它:

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

Apple会说些什么吗?

1 个答案:

答案 0 :(得分:0)

不要这样做。

Apple在the Clang documentation中确实有话要说:

  

不建议使用__attribute__((NSObject)) typedef。如果绝对有必要使用此属性,请非常明确地使用typedef,并且不要假设它将由__typeof和C ++模板参数替换等语言功能保留。

CFGetRetainCountmeaningless。比无意义更糟糕,因为你认为它可能意味着什么。