Set related objects for literal value in Swift

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; } 
+1
ios swift
Dec 24 '14 at 10:06
source share
1 answer

NSData is part of a class cluster, so your own init method does not have to be called, for example

 let d = NSMutableData() 

doesn't use your init method. The next problem is that the init method call itself is recursive, so

 let d = NSData() 

stack overflow failed. Also note that the Objective-C code is undefined, as it replaces the method in the class extension.

So, it’s better to remove your user initialization and change getter to return the default value if the associated object has not been set. This can be easily achieved with optional casting ( as? Int ) and nil-coalescing ( ?? ):

 extension NSData { var position: Int { get { return objc_getAssociatedObject(self, &xoAssociationKey) as? Int ?? 0 } set { objc_setAssociatedObject(self, &xoAssociationKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } } } 
+4
Dec 24 '14 at 10:52
source share
— -



All Articles