1. 程式人生 > >iOS動態新增和獲取屬性

iOS動態新增和獲取屬性

我們可以利用

objc_setAssociatedObject

objc_getAssociatedObject

來為類動態新增和獲取屬性



static char dynamicKey;
    NSArray *array = @[@"4", @"5", @"6"];
    NSString *dymaicString = @"動態新增屬性";
    objc_setAssociatedObject(array, &dynamicKey, dymaicString, OBJC_ASSOCIATION_RETAIN);
    
    NSString *associatedObject = (NSString *)objc_getAssociatedObject(array, &dynamicKey);
    NSLog(@"%@",associatedObject);