Where to store "global" objects in iOS

Possible duplicate:
How and where should I store instances of objects that are required globally in my iOS app?

I have some global object (used in almost all application screens), and basically they are created right after the application starts. I want to have access to these objects from all my ViewControllers (nothing else, just ViewControllers). Where to store it?

I think of @property in AppDelegate , but I think (but I could be wrong) this is an ugly solution.

Objects can be quite complex, they are not simple types.

+6
source share
5 answers

You can make global objects available by placing them in a class with class methods for accessing global objects, introducing +(void)load to prepare these objects and storing them in static variables.

Title:

 @interface GlobalObjects +(void)load; +(MyObject1*)myObject1; @end 

Implementation:

 #import "GlobalObjects.h" static MyObject1* _myObject1 = nil; @implementation GlobalObjects +(void)load { _myObject1 = [[MyObject1 alloc] init]; } +(MyObject1*)myObject1 { return myObject1; } @end 

Using:

 MyObject1 *shared = [GlobalObjects myObject1]; 

You can also make a static variable inside your method for lazy initialization.

+10
source

Yes, I use the App Delegate properties and then access them by adding the sharedApplication delegation property.

 __weak AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 

Hope this helps,

Jonathan

+3
source

@property in AppDelegate is a good solution. You can also use singleton.

+1
source

You delegate the application perfectly if you just have a bunch of objects.

Otherwise, you can create a kind of "model object" containing all of your global data.

Or you can save them using Core Data, if they have any structure at all.

But, as I said, if you have only a few objects, the application delegate will just be fine.

+1
source

if it is used only for view controllers, you can consider storing it in a view controller of the highest level, which actually needs access to a common object (when creating / clicking new controllers, setting this property with reference counting).

thus, you might think that the main view controller fills the detailed view controllers with their contents / models.

what really departs from qualifications as (and a burden) global.

+1
source

Source: https://habr.com/ru/post/920814/


All Articles