Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where to store "global" objects in iOS [duplicate]

Possible Duplicate:
How or where should I store object instances that I require globally within my iOS app?

I have some global object (uses in almost all Application Screens) and mostly they are created right after application starts. I want to have access to this objects from all my ViewControllers (nothing else, only ViewControllers). Where to store it?

I think about @property in AppDelegate but i think (but I can be wrong) this is a ugly solution.

Objects can be quite complex, this is not a simple types.

like image 715
Jakub Avatar asked Jul 18 '12 16:07

Jakub


5 Answers

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

Header:

@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

Usage:

MyObject1 *shared = [GlobalObjects myObject1];

You could also make the variable static inside its method for lazy initialization.

like image 73
Sergey Kalinichenko Avatar answered Nov 02 '22 13:11

Sergey Kalinichenko


Yeah I use properties of the App Delegate, then access them by casting the sharedApplication delegate property.

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

Hope this helps,

Jonathan

like image 39
Jonathan King Avatar answered Nov 02 '22 12:11

Jonathan King


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

like image 1
divol Avatar answered Nov 02 '22 14:11

divol


You app delegate is fine if you just have a bunch of objects.

Otherwise you might build a sort of "model object" containing all of your global data.

Or, you might store them with Core Data, if they have any structure at all.

But, as I said, if you have just a couple of objects, the app delegate will just do fine.

like image 1
sergio Avatar answered Nov 02 '22 13:11

sergio


if it's only used among view controllers, you might consider storing it in the highest level view controller which actually needs access to the shared object (when creating/pushing new controllers, set that reference counted property).

in this way, you might think of the master view controller populating the detail view controllers with their content/models.

that's really stepping away from qualification as (and burdens of) a global.

like image 1
justin Avatar answered Nov 02 '22 13:11

justin