Swift - Why init(coder) is required in AFHTTPSessionManager?

吃可爱长大的小学妹 提交于 2019-12-22 18:08:32

问题


I'm not very experienced in iOS development. While making subclass of AFHTTPSessionManager XCode suggested me to include required init(coder):

import UIKit

let _sharedAPIManager = APIManager(baseURL: NSURL(string: API_URL)!)

class APIManager: AFHTTPSessionManager {

    /**
     * Singleton service 
     * (https://github.com/hpique/SwiftSingleton)
     */
    class var sharedInstance : APIManager {
        return _sharedAPIManager
    }

    init(baseURL url: NSURL!) {
        super.init(baseURL: url, sessionConfiguration: nil)

        self.responseSerializer = AFJSONResponseSerializer() as AFJSONResponseSerializer
        self.requestSerializer = AFJSONRequestSerializer() as AFJSONRequestSerializer

        self.requestSerializer.setValue(API_KEY, forHTTPHeaderField: "X-Api-Key")
        self.requestSerializer.setValue("3", forHTTPHeaderField: "X-Api-Version")
    }

    // this was inserted by XCode
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

My main question is why it's required? As far as I know NSCoder deals with storyboards related code (e.g. called when the nib loads).

Related question Class does not implement its superclass's required members contains some info but does it mean that all Swift classes that extend Objective-C ones will need it?


回答1:


initWithCoder: and encodeWithCoder: are used any time you encode and decode objects, usually for writing to / reading from disk. You're right that storyboards use this, but it's also a very common way to save data in between app launches.

AFHTTPSessionManager implements this method so that you can encode your session manager if you want. Because it's implemented there, you must override it in your subclass, and set or decode any non-optional properties before you call super.



来源:https://stackoverflow.com/questions/29320083/swift-why-initcoder-is-required-in-afhttpsessionmanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!