Well, this is possibly a duplicate question.
I found several questions like this one: Is there a way to set related objects in Swift?
However, I want to add the Int property to the swift extension , and these answers in the link above do not work.
Here is my code:
import ObjectiveC var xoAssociationKey: UInt8 = 0 extension NSData { var position: Int { get { return objc_getAssociatedObject(self, &xoAssociationKey) as Int } set { objc_setAssociatedObject(self, &xoAssociationKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } } override convenience init() { self.init() position = 0 } }
And I get fatal error: unexpectedly found nil while unwrapping an Optional value every time I refer to position
FYI, I found a solution for this error in Objective-C , and I'm looking for a quick solution. Here is my code in the C lens, if you're interested:
static char PROPERTY_KEY; @implementation NSData (Extension) @dynamic position; - (NSInteger)position { return [objc_getAssociatedObject(self, &PROPERTY_KEY) integerValue]; } - (void)setPosition:(NSInteger)position { // Must convert to an object for this trick to work objc_setAssociatedObject(self, &PROPERTY_KEY, @(position), OBJC_ASSOCIATION_COPY); } - (instancetype)init { self = [super init]; if (self) { self.position = 0; } return self; }
ios swift
Pham Hoan Dec 24 '14 at 10:06 2014-12-24 10:06
source share