ABRecordSetValue返回的CFErrorRef的内存管理
考虑一些涉及error handling的典型CF代码,比如说:
ABRecordRef aRecord = ABPersonCreate(); CFErrorRef anError = NULL; ABRecordSetValue(aRecord, kABPersonFirstNameProperty, CFSTR("Joe"), &anError);
在此代码之后如何处理anError
? 我是否必须保留它,以确保它不会消失,然后再释放它? 或者我已经是主人了,我只需要稍后发布它?
在Core Foundation框架中,调用者始终有责任释放通过CFErrorRef *
参数返回的错误。 例如,这是来自CFBundle.h
的头文件注释:
CF_EXPORT Boolean CFBundlePreflightExecutable(CFBundleRef bundle, CFErrorRef *error) CF_AVAILABLE(10_5, 2_0); /* This function will return true if the bundle is loaded, or if the bundle appears to be */ /* loadable upon inspection. This does not mean that the bundle is definitively loadable, */ /* since it may fail to load due to link errors or other problems not readily detectable. */ /* If this function detects problems, it will return false, and return a CFError by reference. */ /* It is the responsibility of the caller to release the CFError. */
机会是AB框架使用相同的约定。
根据“CFError.h”,其中定义了CFErrorRef:即
typedef struct __CFError * CFErrorRef; // line 43 in CFError.h
如果你滚动到顶部,你会在第14行到第22行看到这个:
CFError *error; if (!ReadFromFile(fd, &error)) { ... process error ... CFRelease(error); // If an error occurs, the returned CFError must be released. } It is the responsibility of anyone returning CFErrors this way to: - Not touch the error argument if no error occurs - Create and assign the error for return only if the error argument is non-NULL
因此我们似乎需要自己发布CFErrorRef!