Associative Object を Category に付けたときにリリースするためには dealloc を swizzling しなきゃならないのかと思ったら自動で開放されるそうなので試してみた。
だったら、 property も自動で開放してくれていいのではと思ったがやっぱりダメだった。
Objective-C ってこういうコードサンプル書くときには冗長で面倒ですね。もっとシンプルに書けないかな?
main.m
/* clang main.m -o main -framework Cocoa && ./main */
# include <stdio.h>
# import <Cocoa/Cocoa.h>
# import <objc/runtime.h>
# define TRACE(msg) printf("%s %s\n", __PRETTY_FUNCTION__, msg)
@interface Content : NSObject
@property (nonatomic, retain) NSString *msg;
@end
@implementation Content
@synthesize msg=_msg;
- (id)initWithMessage:(NSString *)msg
{
self = [super init];
if (self) {
self.msg = msg;
}
return self;
}
- (void)dealloc
{
TRACE(self.msg.UTF8String);
self.msg = nil;
[super dealloc];
}
@end
@interface Container : NSObject
@property (nonatomic, retain) Content *content;
@end
static char associativeKey;
@implementation Container
@synthesize content=_content;
- (id)init
{
self = [super init];
if (self) {
id associatedObject = [[[Content alloc] initWithMessage:@"associatedObject"] autorelease];
objc_setAssociatedObject(self, &associativeKey, associatedObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
self.content = [[[Content alloc] initWithMessage:@"property"] autorelease];
}
return self;
}
- (void)dealloc
{
TRACE("");
self.content = nil;
[super dealloc];
}
@end
int main(int argc, char **argv)
{
@autoreleasepool {
[[Container new] autorelease];
}
return 0;
}
$ clang main.m -o main -framework Cocoa && ./main
-[Container dealloc]
-[Content dealloc] property
-[Content dealloc] associatedObject