krypton36 krypton36 - 7 months ago 67
iOS Question

Swift: Stored Properties in Extensions unrecognized selector exception

I have an extension of NSURLSessionDownloadTask, inside of this Extension, I created a stored property called 'id' using Objective C Associated Objects. When I try to set the property, I get 'an unrecognized selector sent to instance'. Here's my code below:

extension NSURLSessionDownloadTask {

private struct AssociatedKeys {
static var id: String?

var id: String? {
get {
return objc_getAssociatedObject(self, & as? String
set {
if let newValue = newValue {
objc_setAssociatedObject(self, &, newValue as String?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)

Later on;

let task = session.downloadTaskWithURL(url) = identifier


I can not fully explain it, but the problem seems to be that session.downloadTaskWithURL(url) returns an instance of some internal subclass __NSCFLocalDownloadTask.

If you define the extension as an extension of NSURLSessionTask instead of NSURLSessionDownloadTask

extension NSURLSessionTask { ... }

then it worked in my test.