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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…