我需要为我的新项目使用共享类来重用swift中的对象和函数。我还需要知道如何在另一个类中使用它。 提前致谢 浆果
答案 0 :(得分:1)
嗨请找下面的例子。
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)
}
}
答案 1 :(得分:0)
这是一个简单的例子,说明如何创建2个类并使用第2类中第1类的数据和函数。
首先是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
希望它有所帮助。