开发者

Sharing an object throughout an app

开发者 https://www.devze.com 2023-04-06 13:41 出处:网络
I am currently developing an applica开发者_开发百科tion for the iPhone. The appdelegate shows a splash-screenwhile I\'m caching data (e.g. NSDictionary) for use in a certain view. What is the best way

I am currently developing an applica开发者_开发百科tion for the iPhone. The appdelegate shows a splash-screen while I'm caching data (e.g. NSDictionary) for use in a certain view. What is the best way to call this data from the view I need it in? I don't think passing it along as a variable from view to view until it reaches the view is a correct way to do this.

App Delegate (with Splashscreen that should cache the data to NSDictionary) | View A | SubView | Final View (here I want to use the cached data)

Thanks :-)


If the NSDictionary that you're caching the data in is an ivar of your App Delegate you can access it from anywhere in your app using the following lines:

myAppDelegate *delegate = (myAppDelegate *)[[UIApplication sharedApplication] delegate];
NSDictionary *myData = [delegate cachedData];

Hope that answers your question.


If you have an object that will never be released throughout the entire life of the app, and really want it to be accessible from absolutely anywhere in the app (say, so that a simple debug NSLog from absolutely anywhere in the code can print it's state), then that's what global variables are for. Just assign a global variable with a reference to the object. If you don't mind generating nearly equivalent but microscopically slower and larger code, then assign it to an instance variable in the app delegate with a suitable getter.

Note that using global variables is a violation of encapsulation that won't be very scalable, maintainable or suitable for unit testing, but is perfectly suitable for a small app which is not much larger than most objects would encapsulate anyway.

0

精彩评论

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