Your New Friends: Obj-C Associated Objects

原创
2014/11/06 21:25
阅读数 15
There are tons of goodies in Snow Leopard for developers, but one of my favorites is associated objects, which allow you to tack arbitrary key/value pairs onto any  NSObject. Since there’s no documentation whatsoever, I thought I’d introduce you. Here’s how you’d store a value with a strong reference:
#import <objc/runtime.h>
objc_setAssociatedObject(obj, key, value, OBJC_ASSOCIATION_RETAIN);
And how you’d get it back:
id value = objc_getAssociatedObject(obj, key);
key can be any  void *; it doesn’t have to implement  NSCopying. See objc/runtime.h for the other memory management flags. If you’re defining a category on a class you didn’t make, associated objects give you a non-hideous way to essentially add instance variables. I use them in  KVO+Blocks to store observer data on objects. Associated objects also come in handy when you need to keep a value around for a little bit, but it’s just not important enough to muddy up your header. Maybe you’re firing off some dialog asynchronously, and you want to free it when the callback is fired. Associated objects save you from having to make an instance variable for that. Here’s a nice Obj-C category wrapping the C API. Enjoy! Update:  Kevin Ballard points out that since the key is just a  void *, you can also do this kind of thing:
static char key;
objc_setAssociatedObject(obj, &key, ...);
This is especially elegant when  key can be method-local—when lazily loading some resource, for instance. Update 2:  Bill Bumgarner further  points out that  _cmd can also be used as the key, since selectors are constant and unique. From:http://blog.andymatuschak.org/post/173646741/your-new-friends-obj-c-associated-objects 结合block来改写UIAlertView和UIActionSheet很有用!
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部