I just want to add a property to UIView
like this,
#import "UIView+Extension.h"
#import <objc/runtime.h>
@implementation UIView (Extension)
- (void)setMaxWidth:(CGFloat)maxWidth {
objc_setAssociatedObject(self, @selector(maxWidth), @(maxWidth), OBJC_ASSOCIATION_ASSIGN);
}
- (CGFloat)maxWidth {
return [objc_getAssociatedObject(self, _cmd) doubleValue];
}
@end
but sometime it's useful, some time is crashed.
I got the crash info in XCode is this line return [objc_getAssociatedObject(self, _cmd) doubleValue];
.
and I got the crash in Bugly is this NSInvalidArgumentException -[_UILabelStringContent doubleValue]: unrecognized selector sent to instance 0x2804fb280
.
So Why this happend. I just set a float value
but get a _UILabelStringContent value
.
PS: My project is in swift 5.0, but I just use Objective-C runtime to add extra properties.
PS2: I used the same code in another Objective-C project, It will not crash.
PS3: It's not always crash.
PS4: I used the this property in UIView
and BaseLabel
, but only crash in BaseLabel
.
PS5: I used it to update frame, I used it in BaseLabel
like this.
override func sizeToFit() {
super.sizeToFit()
if self.maxWidth > 0 {
if numberOfLines != 1 {
let size = self.sizeThatFits(CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude))
self.size = size
} else {
if self.size.width > maxWidth {
self.size.width = maxWidth
}
}
}
}
PS6: Is the crash call by _cmd
in objc_getAssociatedObject(self, _cmd)
??