xcode 如何快速创建模型类并从另一个类中的模型类中获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30914758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 07:20:11  来源:igfitidea点击:

How can Create Model class in swift and get values form model class in another class

iosxcodeswiftxcode6

提问by Das

How can i create model class in Swift. I am getting errors wile accessing values form the model class. Thank you. Here I am attaching my demo project, U can download it

如何在 Swift 中创建模型类。我在从模型类访问值时遇到错误。谢谢你。我附上我的演示项目,你可以下载它

回答by Dharmesh Kheni

This way you can add and get values from model class:

通过这种方式,您可以从模型类中添加和获取值:

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

OutPut will be:

输出将是:

 First name :abcd    Last  name :efghi Bio :biodata

EDIT

编辑

As per your requirement if you want to store object into your model class in AppDelegate then you have to create one global array of type User which will store your objects and when app loads you can append your object into that array with below code:

根据您的要求,如果您想将对象存储到 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
    }

}

Now you can access your save object this way In your ViewController.swiftclass:

现在您可以通过这种方式访问​​您的保存对象在您的ViewController.swift课程中:

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

}

And your OutPut will be:

你的输出将是:

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