【发布时间】:2014-10-15 02:43:06
【问题描述】:
我正在将一个应用程序从 Objective-C 切换到 Swift,我有几个具有存储属性的类别,例如:
@interface UIView (MyCategory)
- (void)alignToView:(UIView *)view
alignment:(UIViewRelativeAlignment)alignment;
- (UIView *)clone;
@property (strong) PFObject *xo;
@property (nonatomic) BOOL isAnimating;
@end
由于 Swift 扩展不接受这样的存储属性,我不知道如何保持与 Objc 代码相同的结构。存储属性对我的应用程序非常重要,我相信 Apple 一定已经为在 Swift 中创建了一些解决方案。
正如jou所说,我正在寻找的实际上是使用关联对象,所以我做了(在另一个上下文中):
import Foundation
import QuartzCore
import ObjectiveC
extension CALayer {
var shapeLayer: CAShapeLayer? {
get {
return objc_getAssociatedObject(self, "shapeLayer") as? CAShapeLayer
}
set(newValue) {
objc_setAssociatedObject(self, "shapeLayer", newValue, UInt(OBJC_ASSOCIATION_RETAIN))
}
}
var initialPath: CGPathRef! {
get {
return objc_getAssociatedObject(self, "initialPath") as CGPathRef
}
set {
objc_setAssociatedObject(self, "initialPath", newValue, UInt(OBJC_ASSOCIATION_RETAIN))
}
}
}
但是我在做的时候得到一个 EXC_BAD_ACCESS:
class UIBubble : UIView {
required init(coder aDecoder: NSCoder) {
...
self.layer.shapeLayer = CAShapeLayer()
...
}
}
有什么想法吗?
【问题讨论】:
-
Objective-C类类别也不能定义实例变量,你是怎么实现这些属性的?
-
不知道为什么您的访问权限不正确,但您的代码不应该工作。您将不同的值传递给 setAssociateObject 和 getAssociatedObject。使用字符串“shapeLayer”作为键是错误的,指针(实际上是地址)才是键,而不是它指向的内容。位于不同地址的两个相同字符串是两个不同的键。查看 Jou 的回答并注意他如何将 xoAssociationKey 定义为全局变量,因此在设置/获取时它是相同的键/指针。
标签: ios swift associated-object