开发者

So very lost on initializing const objects

I have tried many times to understand the const keyword, but it just doesn't work ou开发者_C百科t for me.

I want to declare an object that cannot be changed, which is to say, a constant object. For example, in the .h file:

extern MyClass *use_this_object;

and in the .m file:

MyClass *use_this_object;

+ (void) Initialize {
  use_this_object = [MyClass new];
}

Now, where can I put a const so that other classes can access use_this_object but not modify it (assuming MyClass is immutable), while the MyClass class can initialize the variable?

Is this even possible? Or should I be using a static method to retrive the constant and not declare it extern at all?


There is no such thing as a "const object" in Objective-C. There are const pointers and there are immutable objects. A const pointer to an immutable object is what you're talking about, but you can't allocate those at run time.

For objects that can be allocated at compile time (and I only know of one, NSString), you can do this:

NSString * const kMyString = @"string";

This is a constant pointer to an (immutable) NSString. You read these things right-to-left.

To create what you want, you need a function or method with an internal static like this:

+ (Something *)something {
  static Something *something = nil;
  if (! something) {
      something = [Something new];
  }
  return something;
}

This is preferable to using globals anyway for things other than true constants (like strings and integers).

It is up to you to make sure that Something is immutable.

EDIT Just a note about the above code. This is just an example of how to create a static object at runtime. There are many ways to do it with various trade-offs including using +initialize with a file static (which is currently my preferred way to create a singleton). Don't take the above code as the one-and-only-way. It's just the way that is closest to const because no other part of the program can get directly to the pointer.


I’d use the static method, seems much simpler.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜