Search code examples
iosobjective-ciphoneclassstore

How to store data in class in iOS programming?


The goal, to create a class which contains an array of data to be used throughout the application by other classes.

I have this GlobalObject.h
It declares the array to be used to store the data.

#import <Foundation/Foundation.h>

@interface GlobalObjects : NSObject
@property (retain) NSMutableArray *animals;


-(id)init;
@end

I have this GlobalObject.m.
It contains the NSDictionary data and stores in to the array.

#import <Foundation/Foundation.h>

@interface GlobalObjects : NSObject
@property (retain) NSMutableArray *animals;


-(id)init;
@end


#import "GlobalObjects.h"

@implementation GlobalObjects

@synthesize animals;

-(id)init{
    self = [super init];
    if (self) {
        // Define the data
        NSArray *imagesValue = [[[NSArray alloc] initWithObjects:@"dog.wav",@"cat.png",@"bird.png",nil] autorelease];
        NSArray *audioValue =[[[NSArray alloc] initWithObjects:@"dog.wav",@"cat.wav",@"bird.wav",nil] autorelease];
        NSArray *descriptionValue = [[[NSArray alloc] initWithObjects:@"Dog",@"Cat",@"Bird",nil] autorelease];

        // Store to array
        for (int i=0; i<8; i++) {
            NSDictionary *tempArr = [NSDictionary dictionaryWithObjectsAndKeys:[imagesValue objectAtIndex:i],@"image", [audioValue objectAtIndex:i],@"audio", [descriptionValue objectAtIndex:i], @"description", nil];
            [self.animals addObject:tempArr];
        }
    }
    return self;
}
@end

Here's how I call it.

// someOtherClass.h
#import "GlobalObjects.h"
@property (nonatomic, retain) GlobalObjects *animalsData;

// someOtherClass.m
@synthesize animalsData;
self.animalsData = [[[GlobalObjects alloc] init] autorelease];
NSLog(@"Global Object %@ ",self.animalsData.animals);

Now the problem is, when I call this array in another class, it always returns null.

I'm new to iOS programming. So probably my method is wrong?


Solution

  • You forgot to allocate the animals array in the init method of "GlobalObjects":

    self.animals = [[NSMutableArray alloc] init];
    

    If you don't do this, self.animals is nil and addObject has no effect.

    Since you do not use ARC, remember to release the array in dealloc.

    EDIT: As @H2CO3 and @Bastian have noticed, I forgot my pre-ARC lessons. So the correct way to allocate self.animals in your init method is

    self.animals = [[[NSMutableArray alloc] init] autorelease];
    

    and in dealloc you have to add

    self.animals = nil;
    

    before calling [super dealloc]. I hope that I got it right now!