NA000022 NA000022 - 7 months ago 38
Swift Question

Pass Viewcontroller as Parameter

I am making a class for sharing. This class will be used many times in my project. So I have defined many methods there with a parameter that specify refrence UIViewcontroller on which i want to present something like

SLComposeViewController
. I just want to ask one thing that is it normal to pass a UIVIewcontroller as parameter or it is not recommended to pass UIVIewController as parameter.

// ViewController Class
class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func shareFacebook(sender: UIButton) {
let sharePanelObj = SharePanel()
sharePanelObj.facebookShare(self)
}

@IBAction func shareTwitter(sender: UIButton) {
}
}


// Reusable Base Class
class SharePanel: NSObject {

func facebookShare (refrenceViewController:UIViewController) -> () {
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) {
let fbShare:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)

refrenceViewController.presentViewController(fbShare, animated: true, completion: nil)

} else {
let alert = UIAlertController(title: "Accounts", message: "Please login to a Facebook account to share.", preferredStyle: UIAlertControllerStyle.Alert)

alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
refrenceViewController.presentViewController(alert, animated: true, completion: nil)
}
}
}

Answer

I don't see any issues with sending your view or viewController as a parameter for this use but it might be cleaner to add those methods as extensions to UIViewController and then the you can just act on self instead of the parameter.

One thing to consider might be the memory management if you keep a reference to the view controller. That might screw a bit with the load and unload of the views that are often relied upon to setup the views.

Comments