简体   繁体   English

如何在Swift3中从另一个类获取数据

[英]How to Get data from another class in swift3

I have one swift file and in which I have kept my common function that I need every time so when I am accessing that function I am not getting value 我只有一个快速文件,并且每次都保留了我所需的通用功能,因此当我访问该功能时,我不会获得价值

Myfirst class 我的头等舱

import Foundation
import UIKit

class test1
{
    var mydata = NSMutableArray()


    //MY COMMON FUNCTION

    func loadMoredata(create_at:String)->NSMutableArray
    {
        **//////My CODE**
        //getting correct data
         print(mydata)
         return mydata
    } 
}

Mysecond Class 我的第二课

override func viewWillAppear(_ animated: Bool)
{
        //Calling that function
        // not getting data here or empty array
        let dt:NSMutableArray = test1().loadMoredata(create_at: "0")

        // not getting data here or empty array
        print(test1().mydata)
}

You dont get anything back from your function since your mydata property is an instance property. 由于mydata属性是实例属性,因此您不会从函数中得到任何回报。 Hence, every test1 object you create, will have its own mydata property with its own data. 因此,您创建的每个test1对象都将具有自己的mydata属性和自己的数据。

If you want store global state you could make test1 a singleton class, where mydata is globally accessible. 如果要存储全局状态,可以将test1单例类,在该类中mydata可以全局访问。

class test1
{
   static let shared = test1()
   var mydata = NSMutableArray()

   private init(){}


   //MY COMMON FUNCTION

   func loadMoredata(create_at:String)->NSMutableArray
   {
       **//////My CODE**
       //getting correct data
        print(mydata)
        return mydata
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM