ios – 如何在Swift中存储属性,就像我在Objective-C上一样?

我将一个应用程序从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代码相同的结构。存储的属性对我的应用程序非常重要,我相信苹果必须创建一些解决方案在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中,您不能将存储属性添加到现有类。如果你扩展一个Objective-C类(UIView绝对是一个),你仍然可以使用Associated Objects来模拟存储的属性:

为Swift 1

import ObjectiveC

private var xoAssociationKey: UInt8 = 0

extension UIView {
    var xo: PFObject! {
        get {
            return objc_getAssociatedObject(self, &xoAssociationKey) as? PFObject
        }
        set(newValue) {
            objc_setAssociatedObject(self, &xoAssociationKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN))
        }
    }
}

关联键是每个关联的唯一的指针。为此,我们创建一个私有全局变量,并使用它的内存地址作为关键与&运算符。关于如何在Swift中处理指针的更多细节参见Using Swift with Cocoa and Objective-C

UPDATED为Swift 2和3

import ObjectiveC

private var xoAssociationKey: UInt8 = 0

extension UIView {
    var xo: PFObject! {
        get {
            return objc_getAssociatedObject(self, &xoAssociationKey) as? PFObject
        }
        set(newValue) {
            objc_setAssociatedObject(self, &xoAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }
}
http://stackoverflow.com/questions/25426780/how-to-have-stored-properties-in-swift-the-same-way-i-had-on-objective-c

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:ios – 如何在Swift中存储属性,就像我在Objective-C上一样?