-
-
Save janodev/11c22c0edea5391a3799 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h> | |
@interface News : NSObject { | |
NSString *_title; | |
} | |
@end | |
@implementation News | |
NSString *_excerpt; | |
-(id)initWithTitle:(NSString*)title excerpt:(NSString*)excerpt { | |
self = [super init]; | |
if (self) { | |
_title = [[NSString alloc] initWithString:title]; | |
_excerpt = [[NSString alloc] initWithString:excerpt]; | |
} | |
return self; | |
} | |
-(NSString*)description { | |
return [NSString stringWithFormat:@"%@, %@",_title,_excerpt]; | |
} | |
@end | |
int main(int argc, char *argv[]) { | |
@autoreleasepool { | |
News *b = [[News alloc] initWithTitle:@"A" excerpt:@"X"]; | |
News *a = [[News alloc] initWithTitle:@"B" excerpt:@"Y"]; | |
NSLog(@"%@",a); | |
NSLog(@"%@",b); | |
} | |
} |
The output of clang -rewrite-objc News.m
looks like this:
struct News{
struct NSObject_IMPL NSObject_IVARS;
NSString *_title;
};
/* @end */
// @implementation News
NSString *_excerpt; // <-- global field to the class
and seems to work as a class variable, which I thought Objective-C didn't have. Where is this documented by Apple? I wish there was a complete specification of the language to look up this stuff.
Any variable declared outside of @interface … {}
or @implementation … {}
is treated as a regular C variable. In your example, _excerpt
is a global (file scope) variable with static storage duration and could equivalently be placed at the top of the file before @interface
, or between @interface
and @implementation
, or between the implementation of two methods — it’s the same mechanism where file scope variables in C are defined outside of a function block.
Variables with static storage duration can be used to realise class variables, a concept that doesn’t exist in Objective-C.
Thank you, that clears it up. :)
Result is