如何创建共享 class 并在 swift 中的另一个 class 中使用它

How to create a shared class and use it in another classes in swift

我需要为我的新项目使用一个共享的 class,以便在 swift 中重用对象和函数。我还需要知道如何在另一个 classes 中使用它. 提前致谢 贝瑞

这里是一个简单的示例,说明如何创建 2 个 class 并在第二个 class 中使用第一个 class 中的数据和函数。

第一个ViewController:

class FirstViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
    let yourSharedValue: String = "Hello"
}
func yourSharedFunction() {
print("your func")
}

秒ViewController:

class SecondViewController: UIViewController {
let sharedData = FirstViewController() // assigning the data and functions from 1st view controller to variable 'sharedData'
override func viewDidLoad() {
    super.viewDidLoad()
let someString = sharedData.yourSharedValue // here you assign the value from 1st View controller to the value in 2nd view controller
sharedData.yourSharedFunction() // here you call the function from 1st VC

希望对您有所帮助。

您好,请查找以下示例。

class SharedClass: 
    NSObject {
        var email:NSString=""
        var image:NSString=""
        var name:NSString=""
        var memberID:NSString=""
        var agencyName:NSString=""
        var billedAmount:NSString=""
        var paidAmount:NSString=""

        class var sharedInstance: SharedClass {
            struct Static {
                static var onceToken: dispatch_once_t = 0
                static var instance: SharedClass? = nil
            }

            dispatch_once(&Static.onceToken) {
                Static.instance = SharedClass()
            }

            return Static.instance!
        }

        func logout(){
            let defaults = NSUserDefaults.standardUserDefaults()
            defaults.setObject(nil, forKey: "user_id")
            defaults.setObject(nil, forKey:  "first_name")
            defaults.setObject(nil, forKey: "user_image")
            defaults.setObject(nil, forKey:   "email")
            defaults.setObject(nil, forKey: "fb_token")
            defaults.synchronize()
            print(defaults.objectForKey("user_id"))

            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

            // appDelegate.userID = ""
            //print(appDelegate.userID)
        }

        func alert(viewController : UIViewController, message : NSString) {
            let alert = UIAlertController(title: "Message", message: message as String, preferredStyle:UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Cancel, handler: nil))
            viewController.presentViewController(alert, animated: true, completion: nil)
        }
    }