, , , , ...
, , , , objc_setAssociatedObject, :
Memento *m = [[[Memento alloc] init] autorelease];
objc_setAssociatedObject(self, kMementoTagKey, m, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
, dealloc ed. , self - , NSKVODeallocateBreak, .
, retain ed (- OBJC_ASSOCIATION_RETAIN_NONATOMIC), release d , dealloc ed... dealloc , . : ! , , , , dealloc ed! , owner ( retain!), , dealloc .
.m :
#import <objc/runtime.h> // So we can use objc_setAssociatedObject, etc.
#import "TargetClass+Category.h"
@interface TargetClass_CategoryMemento : NSObject
{
GLfloat *_coef;
}
@property (nonatomic) GLfloat *coef;
@property (nonatomic, assign) id owner;
@end
@implementation TargetClass_CategoryMemento
-(id)init {
if (self=[super init]) {
_coef = (GLfloat *)malloc(sizeof(GLfloat) * 15);
}
return self;
};
-(void)dealloc {
free(_coef);
if (_owner != nil
&& [_owner respondsToSelector:@selector(associatedObjectReportsDealloc)]) {
[_owner associatedObjectReportsDealloc];
}
[super dealloc];
}
@end
@implementation TargetClass (Category)
static NSString *kMementoTagKey = @"TargetClass+Category_MementoTagKey";
-(TargetClass_CategoryMemento *)TargetClass_CategoryGetMemento
{
TargetClass_CategoryMemento *m = objc_getAssociatedObject(self, kMementoTagKey);
if (m) {
return m;
}
m = [[[TargetClass_CategoryMemento alloc] init] autorelease];
m.owner = self;
objc_setAssociatedObject(self, kMementoTagKey, m, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
return m;
}
-(void) doStuff
{
CCSprite_BlurableMemento *m = [self CCSprite_BlurableGetMemento];
}
-(void) associatedObjectReportsDealloc
{
NSLog(@"My associated object is being dealloced!");
}
@end
, - (, S.O.), factory . , memento dealloc , , dealloc ed
:
- ,
OBJC_ASSOCIATION_RETAIN_NONATOMIC, . - , memento/state
dealloc ed , dealloc ed... , , . owner retain, , dealloc ed!- , ,
OBJC_ASSOCIATION_RETAIN_NONATOMIC release d , dealloc ed, , , , , ,. - ,
associatedObjectReportsDealloc dealloc TargetClass - ! , - TargetClass, ! , .
, , , . swizzling - . , . , , , dealloc s!