如何在swift中创建Model类并从另一个类中获取值形成模型类 [英] How can Create Model class in swift and get values form model class in another class

查看:969
本文介绍了如何在swift中创建Model类并从另一个类中获取值形成模型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Swift中创建模型类。我从错误中获取错误,从模型类中访问值。谢谢。 我在这里附加我的演示项目,你可以下载它

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

推荐答案

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

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将是:

 First name :abcd    Last  name :efghi Bio :biodata

编辑

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

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:

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 类:

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

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

}

而你的OutPut将是:

And your OutPut will be:

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

这篇关于如何在swift中创建Model类并从另一个类中获取值形成模型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆