I need to use a shared class for my new project for reusing objects and functions in swift .I also need to know how this can be used in another classes. Thanks in Advance Berry
Asked
Active
Viewed 1,508 times
-2
-
2Possible duplicate of [Where to put reusable functions in IOS Swift?](http://stackoverflow.com/questions/30633408/where-to-put-reusable-functions-in-ios-swift) – Shad Jul 29 '16 at 06:01
2 Answers
1
Here is a simple example of how to create 2 classes and using data and functions from 1st class in the 2nd class.
first ViewController:
class FirstViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let yourSharedValue: String = "Hello"
}
func yourSharedFunction() {
print("your func")
}
second 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
Hope it helps.

Tung Fam
- 7,899
- 4
- 56
- 63
1
Hi Please find the below example .
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)
}
}

Frank Pavageau
- 11,477
- 1
- 43
- 53

Rajeev Radhakrishnan
- 66
- 5
-
let sharedClass : SharedClass = SharedClass.sharedInstance for using it in another classs – Rajeev Radhakrishnan Jul 29 '16 at 10:34
-