如何在swift中创建Model类并从另一个类中获取值的模型类

时间:2015-06-18 11:58:15

标签: ios xcode swift xcode6

如何在Swift中创建模型类。我从错误中获取错误,从模型类中访问值。谢谢。 Here I am attaching my demo project, U can download it

1 个答案:

答案 0 :(得分:4)

这样您就可以从模型类中添加和获取值:

var user = User(firstName: "abcd", lastName: "efghi", bio: "biodata")
print("\n First name :\( user.firstName) \t Last  name :\( user.lastName) Bio :\( user.bio)")

OutPut将是:

 First name :abcd    Last  name :efghi Bio :biodata

修改

根据您的要求,如果您想将对象存储到AppDelegate中的模型类中,那么您必须创建一个User类型的全局数组,它将存储您的对象,当应用程序加载时,您可以使用下面的代码将对象追加到该数组中:

import UIKit
import CoreData

// Global array
var userData = [User]()

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        let user = User(firstName: "Silviu", lastName: "Pop", bio: "I f**ing ♡ Swift!!!")
        //Add object into userData
        userData.append(user)
        // Override point for customization after application launch.
        return true
    }

}

现在,您可以通过以下方式访问保存对象:ViewController.swift类:

override func viewDidLoad() {
    super.viewDidLoad()
    let user = userData
    println(user[0].firstName)
    println(user[0].lastName)
    println(user[0].bio)

}

你的OutPut将是:

Silviu
Pop
I f**ing ♡ Swift!!!