以下实验结论表明,本地文本属性在分类属性之前设置,因此该值可以安全地被分类设置器覆盖。
一个标签类别:
#import <UIKit/UIKit.h>
@interface UILabel (Thingy)
@property (nonatomic, strong) IBInspectable NSString *thingy;
@end
#import "UILabel+Thingy.h"
#import <objc/runtime.h>
@implementation UILabel (Thingy)
- (NSString *)thingy {
return objc_getAssociatedObject(self, @selector(thingy));
}
- (void)setThingy:(NSString *)thingy {
NSLog(@"setting thingy to '%@', my text is currently '%@'", thingy, self.text);
objc_setAssociatedObject(self, @selector(thingy), thingy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
在IB中,设置可检查类别属性和文本属性...
![enter image description here](https://istack.dev59.com/uYjMN.webp)
包含视图控制器中有少量的仪表设置:
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"didLoad text is '%@' and thingy is '%@'", self.label.text, self.label.thingy);
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSLog(@"willAppear text is '%@' and thingy is '%@'", self.label.text, self.label.thingy);
}
运行它,NSLog输出表明,在从nib唤醒期间,本地属性在类别属性设置程序被调用之前已经被设置...
引用:
...[794:41622]将thingy设置为'thingy值',我的文本当前为'text value'
...[794:41622] didload文本为'text value'和thingy为'thingy值'
...[794:41622] willappear文本为'text value'和thingy为'thingy值'
在类别属性设置器中设置标签的文本属性会导致(我测试过了)文本属性被覆盖为thingy属性,因为文本属性首先被初始化。
在XML格式呈现的XIB文件中可以看到进一步的证据...
<label opaque="NO" (... all the native properties) text="text value" (...) id="XAM-6h-4fn">
<rect key="frame" x="274" y="147" width="278" height="34"/>
(... and so on)
<userDefinedRuntimeAttributes>
<userDefinedRuntimeAttribute type="string" keyPath="thingy" value="thingy value"/>
</userDefinedRuntimeAttributes>
</label>
这句话的意思是:通过“先序遍历”来实例化和初始化视图,以此在设置(父标签)标签属性之前就设置(子标签) userDefinedRuntimeAttributes。