This was particularly interesting to me due to the &error addressing and the use of “as?” to test the error. I’m in a bit of a rush right now so I apologize for the brevity of the explanation. I’ll try to fill it out more later when I have some time.
func DataFromURL(url : NSURL) -> (NSData?) { var error : NSError? = nil let data : NSData? = NSData.dataWithContentsOfURL( url, options: NSDataReadingOptions.fromMask(0), error: &error) if (data == nil) { if let theError = error as? NSError { let reason : String? = theError.localizedDescription println("Error reading from URL \(url) : \(reason)") return nil } } return data } func DataFromURL(urlString : NSString) -> (NSData?) { var url = NSURL(string: urlString) let standard = url.resourceSpecifier.hasPrefix("//") if (!standard) { url = NSURL(fileURLWithPath: urlString) } if (url === nil) {return nil} return DataFromURL(url) }
In this one, I needed to get a void * to pass for the key, again leading to an interesting solution. By the way, I haven’t debugged the actual associated object stuff (I’ll update this when I do) so please just note the CConstVoidPointer bit. (Update: it all seems to be working in my tests.)
var sharedObserverSelector : Selector = "observers" var sharedObserversKey : CConstVoidPointer = &sharedObserverSelector extension UIViewController { func setObservers(array : NSMutableArray) { objc_setAssociatedObject(self, sharedObserversKey, array, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } func observers() -> (NSMutableArray) { let object : AnyObject? = objc_getAssociatedObject(self, sharedObserversKey) if (object === nil) { let array = NSMutableArray() self.setObservers(array) return array } return object as NSMutableArray }
4 Comments
Thanks for this, it was handy.
What did you import? I get used of undeclared type CConstVoidPointer
Same here CConstVoidPointer is not there
Nick, I wrote this up way last year. Things have changed a lot since then. You can pretty much disregard this entire post now! 🙂