static initializers in objective C

倖福魔咒の 提交于 2019-12-21 04:12:08

问题


How do I make static initializers in objective-c (if I have the term correct). Basically I want to do something like this:

static NSString* gTexts[] = 
{
    @"A string.",
    @"Another string.",
}

But I want to do this more struct-like, i.e. have not just an NSString for each element in this array, but instead an NSString plus one NSArray that contains a variable number of MyObjectType where MyObjectType would contain an NSString, a couple ints, etc.


回答1:


Since NSArrays and MyObjectTypes are heap-allocated objects, you cannot create them in a static context. You can declare the variables, and then initialize them in a method.

So you cannot do:

static NSArray *myStaticArray = [[NSArray alloc] init....];

Instead, you must do:

static NSArray *myStaticArray = nil;

- (void) someMethod {
  if (myStaticArray == nil) {
    myStaticArray = [[NSArray alloc] init...];
  }
}

This happens to work with constant strings (@"foo", etc), because they are not heap-allocated. They are hardcoded into the binary.




回答2:


It is very important that you make sure that your static initialization is thread-safe (available in iOS 4.1+)!!!

static NSArray *myStaticArray = nil;

- (void) someMethod {
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    myStaticArray = [[NSArray alloc] init...]
  });
}



回答3:


here's one way, if you can live with an objc++ translation:

#import <Foundation/Foundation.h>

namespace { // ok, this storage should preferably be in a function/deferred
    static struct sa { NSString* const s; NSArray* const a; } r = {
      [[NSString alloc] initWithString:@"hello"],
      [[NSArray alloc] initWithObjects:@"w", @"o", @"r", @"l", @"d", @"= =", nil]
    };
}

int main(int argc, const char* argv[]) {
  NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  NSLog(@"\n\n%@...\n\n...\n%@", r.s, r.a);
  [pool drain];
  return 0;
}



回答4:


The +initialize method is called automatically the first time a class is used, before any class methods are used or instances are created.

+ (void) initialize {
  if (self == [MyClass class]) {
    // Once-only initializion
  }
  // Initialization for this class and any subclasses
}

+initialize is inherited by subclasses, and is also called for each subclasses that doesn't implement an +initialize of their own. This can be especially problematic if you naively implement singleton initialization in +initialize. The solution is to check the type of the class variable.

p.s You should never call +initialize yourself.



来源:https://stackoverflow.com/questions/5012935/static-initializers-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!