Swift 2.2单身

时间:2016-05-13 05:48:01

标签: swift

我是Swift的新手。我试图从Web服务解析一些JSON数据,并想要一个单独的用户类。但我坚持创建单例。这是我的代码:

import Foundation
class User {
   private var success: String
   private var userId: String
   private var name: String
   private var gender: String
   private var email: String
   private var userObject = [User]()

    class  var sharedInstane:User {
        struct Singleton {
            static var onceToken: dispatch_once_t = 0
            static var instance:User? = nil
        }
        dispatch_once(&Singleton.onceToken){
            Singleton.instance = User()
        }
        return Singleton.instance!
    }

    private init(success: String, userId: String, name: String, gender:  String, email: String)
    {
        self.success = success
        self.userId = userId
        self.name = name
        self.gender = gender
        self.email = email
    }
    convenience init(dictionary: [String:AnyObject]) {
    let success = dictionary["success"] as? String
    let userId = dictionary["userId"] as? String
    let name = dictionary["name"] as? String
    let gender = dictionary["gender"] as? String
    let email = dictionary["email"] as? String
     self.init(success: success!, userId: userId!, name: name!,  gender: gender!, email: email!, )
    }

    func callWebserviceToLoadUserInfo (url:String, param:[String:AnyObject],completeHandler:(Bool?,String) -> ())

    {
     let connection = ServerConnection()
     connection.getJSONDataForWebService(url, params: param) { (response, error) in
     // code goes here
            var responseDict = response as! [String : AnyObject]
            responseDict = responseDict["responseDict"] as! [String : AnyObject]
               if responseDict["success"] as! String == "1" {
                   for dict in responseDict {
                    let user = User(dictionary: (dict as! [String:AnyObject]))
                       self.userObject.append(user)
                }
             print("user : \(self.userObject[0].name)")
            }else{
                // error goes here
            }
        }
  }

}

任何人都可以帮助我,我该怎么做这个代码?

4 个答案:

答案 0 :(得分:3)

单行示例代码中的单例。

class TheOneAndOnlyKraken {
    static let sharedInstance = TheOneAndOnlyKraken()
    private init() {} //This prevents others from using the default '()' initializer for this class.
}

For more details.

答案 1 :(得分:2)

使用Maheshwar引用的Krakendev's单行单例代码,并将convenience init转换为要使用User.sharedInstance.initialize(dictionary)调用的实例函数:

import Foundation
class User {

    // Here you declare all your properties
    // "private var" and all that jazz

    static let sharedInstance = User()

    private init() {
        // If you have something to do at the initialization stage
        // you can add it here, as long as it does not involve
        // arbitrary values that you would pass as parameters.
    }

    func initialize(dictionary: [String:AnyObject]) {
        // Transfer the values of the dictionary to each `self.property`.
        // Be careful while using `as?` as you may have to deal with    
        // optionals. No need to call `self.init` at the end, because 
        // this is now a regular `func`.
    }

    // Add the rest of your stuff here

}

关于您如何在便利初始值设定项内工作的一个注意事项:如果您执行property = SomeClass.someMethod().someProperty as? SomeType,则property将是SomeType?类型,或Optional(SomeType)。根据{{​​3}},

  

条件形式as?返回您尝试向下转换的类型的可选值。

答案 2 :(得分:1)

虽然User未实例化,但至少有一次sharedInstance将返回nil。在第一次成功实例化User之后,sharedInstance开始返回它,并且由于单例模式需要它而无法实例化另一个User。考虑一下:

class User {

    private static var sharedUser: User?

    class var sharedInstance: User? {

        return sharedUser
    }

    private init(success: String, userId: String, name: String, gender:  String, email: String)
    {
        //User initialization code here
        User.sharedUser = self
    }

    convenience init?(dictionary: [String:AnyObject]) {

        guard User.sharedUser == nil else {
            return nil
        }

        //dictionary parsing code is here
        self.init(success: success!, userId: userId!, name: name!,  gender: gender!, email: email!)
    }
}

客户代码:

User.sharedUser
//return nil

let dict: [String:AnyObject] = ["success": "success", "userId":"userId", "name":"name", "gender":"gender","email":"email"]
User(dictionary: dict)
//creates User

User.sharedUser
//returns just created user

User(dictionary: dict)
//return nil

答案 3 :(得分:0)

您应该考虑创建这两个类,以便User是您的模型类,然后创建一个管理器来处理所有用户(这似乎是您的目标)。

所以在User中删除sharedInstane部分并创建第二个单例类,例如名为UserManager,使用标准方法在Swift中创建单例。然后,您可以保持创建用户的方式,最后只需将其分配给单身人士:

class UserManager {
    static let sharedInstance = UserManager()

    var users = [User]()
}

// in your code:
...
for dict in responseDict {
    let user = User(dictionary: (dict as! [String:AnyObject]))
    UserManager.sharedInstance.users.append(user)
}
...