0

There are several questions that seem similar to this (e.g. Objective C Static Class Level variables) and that I read, but I am still confused. Notably, various answers seem to deal differently with the call to initialize.

I have a class Foo. At runtime, my app interrogates the back-end to find out what "class parameters" should be used for Foo (i.e. these params will be shared across all instances of Foo). I know how to deal with the back-end etc. But I don't know if my Objective-C approach is correct. I should say: it does work. But again: I am not sure what I am doing.

EDIT: I thought it worked. But from time to time, I get a strange exception: libsystem_platform.dylib _os_lock_recursive_abort.

It happens in initialize when I alloc/init the NSDictionary.

Foo.h:

+ (NSDictionary *)parameters;
+ (void)setParameters:(NSDictionary *)params;

Foo.m:

static NSDictionary *parameters = nil;

@implementation Foo

+ (NSDictionary *)parameters{
    return parameters;
}

+ (void)setParameters:(NSDictionary *)params
{
    parameters = params;
}

+ (void)initialize
{
    [super initialize];
    if ((self == [Foo self]) && !parameters) // Is this right??
        parameters = [[NSDictionary alloc] init];
}

@end

... somewhere else, in another class ...

[Foo setParameters:dictionaryOfParams]; 
Community
  • 1
  • 1
PJC
  • 997
  • 7
  • 21

1 Answers1

1

Just a minor improvement.

According to Apples + (void)initialize documentation:

initialize is invoked only once per class.

As you are ignoring the initialize when it is being called from a subclass you could remove the !parameters from the If condition. Because you know for sure that it will run only once.

Nuno Vinhas
  • 528
  • 4
  • 12
  • Thanks Nuno. I just added a comment: I get a strange exception from time to time. So I guess something is not right... – PJC Sep 19 '14 at 15:12