Keep alive object in memory for another class

1

Hello! I have a very simple question, as I have already found a solution for her, but it still seems problematic to me. I'll explain:

I created a web service connection to receive some data, and in the end I am storing this data in a dictionary, which in turn gets saved in an array.

But I need this array to be initialized elsewhere, within the class that will save the data in sqlite. But I do not know how to initialize this array with the data that was received from the web service.

The solution I found was to use AppDelegate. The AppDelegate would have a variable that would get this array, and then I would generate an AppDelegate instance within the class that manages the sqlite database. However, I believe that depending on the amount, and volume of data in the tables, I could overload the AppDelegate, consuming a lot of memory.

Someone would know how to solve this problem!

Thank you.

    
asked by anonymous 15.07.2014 / 18:00

1 answer

3

Your solution is valid (using AppDelegate) but it is poor from the point of view of object orientation. You will be putting in the AppDelegate an attribute that is not logically related to this class. I suggest using the same idea (Singleton), but creating a specific object for the data shared between your classes. This reduces the coupling of the code and increases its cohesion. Example:

@interface SharedData : NSObject

+ (SharedData*)sharedInstance;
@property(nonatomic, copy) NSArray *nodes;

@end

@implementation SharedData

+ (SharedData *)sharedInstance
{
    static SharedData *_sharedInstance = nil;

    static dispatch_once_t instanceOnceToken;
    dispatch_once(&instanceOnceToken, ^{
        _sharedInstance = [[SharedData alloc] init];
    });

    return _sharedInstance;
}
@end

In other classes you access the properties and methods of the singleton in a similar way as you would with AppDelegate, ie through the shared instance, eg

[SharedData sharedInstance].nodes = [NSArray new];

As for memory, this solution is slightly less efficient because it allocates an additional object, but it will not impact performance. Problems may appear if you keep large, complex objects in memory, such as bitmaps. With dictionaries, you will hardly have problems.

    
15.07.2014 / 19:26