Search code examples
iosobjective-cxcodexcode-storyboardassociated-object

User Defined Runtime Attributes and Associated Objects


I'm currently trying to use User Defined Runtime Attributes in Xcode 6 with the following algorithm:

  1. Add custom properties to UIView class using Associated Objects

    #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
    
  2. Set values of these properties through Xcode storyboard enter image description here

  3. 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? What did i miss? Can't i set User Defined Runtime Attributes of custom types?


Solution

  • Well myTags is not allocated in the memory and nor initialised. 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.