我在这里看到了一个非常好的示例:子类化UIButton以添加属性
这是什么?你无法将对象添加到分类中。但是现在通过这个技巧,你可以实现。
那么这是什么?它是如何工作的?
Objective-C对象已经有一些常量IVAR指针对吧?
现在你又添加了一个?他们是如何想出来的呢?
这是一个相当丑陋的符号表示法,我必须承认。
那么这是什么?它是如何工作的?
Objective-C对象已经有一些常量IVAR指针对吧?
现在你又添加了一个?他们是如何想出来的呢?
这是一个相当丑陋的符号表示法,我必须承认。
#import "UIButton+Property.h"
#import <algorithm>
#import <vector>
typedef std::pair<__weak id, __strong id> EntryType;
static std::vector<EntryType> myAR;
@implementation UIButton(Property)
-(void) setProperty:(id)property
{
for (int i=0; i < myAR.size(); ++i) {
if (myAR[i].first == self) {
myAR[i].second = property;
return;
}
}
myAR.push_back(EntryType(self, property));
}
-(id) property
{
/* To save space, periodically erase the dictionary entries for
* UIButton objects that have been deallocated. You can skip this
* part, and even use NSMutableDictionary instead of this C++
* stuff, if you don't care about leaking memory all over the place.
*/
size_t n = myAR.size();
for (size_t i=0; i < n; ++i) {
if (myAR[i].first == nil)
myAR[i] = myAR[--n];
}
myAR.resize(n);
/* Look up "self" in our dictionary. */
for (size_t i=0; i < myAR.size(); ++i) {
EntryType &entry = myAR[i];
if (entry.first == self) {
return entry.second;
}
}
return nil;
}
@end
objc
项目中。关联对象的实现在objc-references.mm
中。看看_object_set_associative_reference
和_object_remove_assocations
函数。第二个函数就是-[NSObject dealloc]
最终调用的函数,是的,在源代码中拼写错误。 - rob mayoff