开发者

How do you pass an object between ViewControllers on iOS?

开发者 https://www.devze.com 2023-03-10 09:33 出处:网络
Using the \"Tab Bar\" template in Xcode 4, each ViewController is created automatically, so I don\'t have the chance to set any properties on a Vie开发者_如何学PythonwController as it\'s created. I wa

Using the "Tab Bar" template in Xcode 4, each ViewController is created automatically, so I don't have the chance to set any properties on a Vie开发者_如何学PythonwController as it's created. I want each ViewController to have access to an object (an instance of FMDB's FMDatabase).

There are a number of questions on StackOverflow relating to this already, but some are assuming that you are creating the VC's by hand, and others recommend using the AppDelegate as a mediator:

MyAppDelegateClass *appDelegate = [[UIApplication sharedApplicaton] delegate];
myLocalProperty = appDelegate.someDataModelProperty;

The above seems rather "hacky" to me. Is there a better way to access a single object from multiple ViewControllers?


Most probable implementation of FMDB's Data base would be to implement it as a Singleton and access it through out the application. Is there any reason for not doing so ?

This link should help you in doing so: How do I make FMDB's database a singleton


To expand on KKK4SO's answer, you could implement the Database as a singleton. Then, have all of your UIViewControllers be a subclassed UIViewController that contains methods to access and modify the Database singleton.


MyAppDelegateClass *appDelegate = [[UIApplication sharedApplicaton] delegate]; myLocalProperty = appDelegate.someDataModelProperty;

There is a spelling error in this code 'sharedApplicaton' is incorrectly spelled it should be 'sharedApplication'.

Shame on me for copy and pasting! Anyway this will work for a quick and dirty way of passing data between ViewControllers etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消