OC 获取关联对象
- (UIView*)backgroundView
{
return objc_getAssociatedObject(self, &kBackgroundViewKey);
}
Swift 获取关联对象——错误的写法
func backgroundView() -> UIView
{
return objc_getAssociatedObject(self, kBackgroundViewKey) as! UIView
}
Swift 获取关联对象——正确的写法
func backgroundView() -> UIView?
{
return objc_getAssociatedObject(self, kBackgroundViewKey) as? UIView
}
设置关联对象 OC 与 Swift 什么区别
OC 设置关联对象
- (void)setBackgroundView:(UIView*)backgroundView
{
objc_setAssociatedObject(self, &kBackgroundViewKey, backgroundView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
Swift 设置关联对象
// 这里的UIView可以是可选类型,也可以不是可选类型
func setBackgroundView(backgroundView:UIView?)
{
objc_setAssociatedObject(self, kBackgroundViewKey, backgroundView, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
强烈推荐:超简单!!! iOS设置状态栏、导航栏按钮、标题、颜色、透明度,偏移等
https://github.com/wangrui460/WRNavigationBar
https://github.com/wangrui460/WRNavigationBar_swift
欢迎关注我的微博:wangrui460