[英]User Defined Runtime Attributes and Associated Objects
I'm currently trying to use User Defined Runtime Attributes in Xcode 6 with the following algorithm: 我目前正在尝试通过以下算法在Xcode 6中使用用户定义的运行时属性:
Add custom properties to UIView class using Associated Objects 使用关联对象将自定义属性添加到UIView类
#define ASSOCIATED_OBJECT_GETTER_AND_SETTER(propertyType, propertyName, propertyNameWithCapital, associationType) \\ -(void)set##propertyNameWithCapital:(propertyType)_value \\ { \\ objc_setAssociatedObject(self, @selector(propertyName), _value, associationType); \\ } \\ -(propertyType)propertyName \\ { \\ return objc_getAssociatedObject(self, @selector(propertyName)); \\ } \\ @interface eMyTags : NSObject @property (nonatomic) NSString* name; @end @implementation eMyTags @synthesize name; @end @interface UIView (MyTags) @property (nonatomic) eMyTags* myTags; @property (nonatomic) NSString* myName; @end @implementation UIView (MyTags) @dynamic myTags, myName; ASSOCIATED_OBJECT_GETTER_AND_SETTER(eMyTags*, myTags, MyTags, OBJC_ASSOCIATION_RETAIN_NONATOMIC); ASSOCIATED_OBJECT_GETTER_AND_SETTER(NSString*, myName, MyName, OBJC_ASSOCIATION_RETAIN_NONATOMIC); @end
Set values of these properties through Xcode storyboard 通过Xcode故事板设置这些属性的值
Access these properties in code during runtime 在运行时通过代码访问这些属性
-(void)viewDidLoad { [super viewDidLoad]; NSLog(@"myName: %@", view.myName); NSLog(@"myTags.name: %@", view.myTags.name); }
When i compile and run the output is: 当我编译并运行时,输出为:
myName: bla
myTags.name: (null)
So why myTags.name
is not set? 那么为什么未设置
myTags.name
? What did i miss? 我错过了什么? Can't i set User Defined Runtime Attributes of custom types?
我不能设置自定义类型的用户定义的运行时属性吗?
Well myTags
is not allocated in the memory and nor initialised. 好吧,
myTags
不在内存中分配,也没有初始化。 On the other hand, the value @"bla" is a string literal which is actually an instance of an NSString
and points to a location in memory. 另一方面,值@“ bla”是一个字符串文字,它实际上是
NSString
的实例,并指向内存中的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.