Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

objective c - Instance variables declared in ObjC implementation file

I was watching the WWDC ARC introduction video and I saw something I've never seen in ObjC before when some Apple engineer talked about a Stack example.

The following code was used for a stack example with ARC:

@implementation Stack 
{ 
    // instance variable declared in implementation context
    NSMutableArray *_array; 
}

- (id)init 
{
   if (self = [super init])
      _array = [NSMutableArray array];
   return self;
}

- (void)push:(id)x 
{
   [_array addObject:x];
}

- (id)pop 
{
   id x = [_array lastObject];
   [_array removeLastObject];
   return x;
}

@end

Please note the instance variable declared right after the @implementation directive.

Now the thing that surprised me, is that an instance variable could actually be declared in the implementation file, without it being a static variable. My questions would be the following:

  • Is this some new construct introduced in the SDK for iOS 5 or has this been possible for a long time?
  • Would it be good practice to declare instance variables in the implementation, if the instance variables are not to be accessed outside the object? It seems way cleaner then the use of the @private directive.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is indeed a new language feature, and if you must declare your ivars (rather than simply declaring properties and letting the compiler generate ivars for you) it's a good practice. Your header files in theory should only expose public interface for your classes; everything else belongs in the implementation.

One caveat is that implementation-file ivars are not visible to subclasses, which can occasionally be a little bit awkward if you have manually generated setters and getters that you need to subclass.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...