devmiles.com
devmiles.com

Reputation: 10014

Settings-like array of NSString objects

I'm only starting with Objective-C and it's still hard for me to do some pretty basic things. Here's what I want to achieve - I need to create a class that would hold all static data of my application which I guess could be represented with a number of NSString ** arrays, such as this one:

NSString *animalNames[NUM_ANIMALS] = {@"fox", @"wolf", @"elephant", @"giraffe"};

I want to be able to access these arrays in a static way from anywhere in my application. Something like this:

StaticData.animalNames[1]

How would I accomplish this in terms of @property, @interface, @synthesize and all this stuff?

Upvotes: 0

Views: 87

Answers (1)

FluffulousChimp
FluffulousChimp

Reputation: 9185

I need to create a class that would hold all static data of my application

Here's an example of what you are talking about. It's a basic singleton class with a static array of your animals.

#import <Foundation/Foundation.h>

@interface Foo:NSObject
+ (id)sharedFoo;
- (NSArray *)animals;
@end

@implementation Foo

static NSArray *animals;

+ (void)initialize {
    animals = [NSArray arrayWithObjects:@"fox",@"wolf",@"giraffe",@"liger",nil];
}

+ (id)sharedFoo {
    static dispatch_once_t pred;
    static Foo *cSharedInstance = nil;

    dispatch_once(&pred, ^{ cSharedInstance = [[Foo alloc] init]; });
    return cSharedInstance;
}

- (NSArray *)animals {
    return animals;
}

@end

int main(int argc, char *argv[]) {
    NSLog(@"Animals = %@",[[Foo sharedFoo] animals]);

}

This application logs the following to the console:

2012-10-08 10:01:46.814 Untitled[77085:707] Animals = ( fox, wolf, giraffe, liger )

EDIT:

If you favor the dot syntax/property notation, you could just implement the following in the class interface:

@property (readonly) NSArray *animals;  

which would let you write:

[Foo sharedFoo].animals

etc.

Upvotes: 2

Related Questions