我的代码是
// UIColor + Theme.h
@interface UIColor (Theme)
@property (nonatomic, copy) NSString *colorName;
@end
// UIColor + Theme.m
static const void *kColorName = "colorName";
@implementation UIColor (Theme)
- (NSString *)colorName {
return objc_getAssociatedObject(self, kColorName);
}
- (void)setColorName:(NSString *)colorName {
objc_setAssociatedObject(self, kColorName, colorName, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
@end
// viewController.m中的代码
NSLog(@"%@", self.view.backgroundColor.colorName);//**print (null)**
UIColor *color1 = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1];
color1.colorName = @"C1";
NSLog(@"%@", color1.colorName);//**print C1**
self.view.backgroundColor = color1;
NSLog(@"%@", self.view.backgroundColor.colorName);//**print (null)**
self.view.backgroundColor.colorName = @"C1";
NSLog(@"%@", self.view.backgroundColor.colorName);//**print (null)**
UIColor *color2 = [UIColor whiteColor];
color2.colorName = @"C2"
self.view.backgroundColor = color2;
NSLog(@%@", color2.colorName);// **print C2**
NSLog(@"%@", self.view.backgroundColor.colorName);// **print C2**
[当我使用[UIColor whiteColor]之类的方法时,self.view.backgroundColor的colorName存在。(color1和self.view.backgroundColor的地址相同)
但是当我使用[UIColor colorWithRed:green:blue:alpha:]之类的方法时,self.view.backgroundColor的colorName为空。(color2和self.view.backgroundColor的地址不同)
也许问题在于有关OC的深层复制,因为self.view.backgroundColor的属性是(nullable,nonatomic,copy)。如何给self.view.backgroundColor.colorName赋值,并使用[UIColor colorWithRed:green:blue:alpha:]之类的方法。
有人可以帮我,我将不胜感激!谢谢!