Skip to content

Instantly share code, notes, and snippets.

@janodev
Last active December 11, 2015 04:38
Show Gist options
  • Save janodev/11c22c0edea5391a3799 to your computer and use it in GitHub Desktop.
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);
}
}
@janodev
Copy link
Author

janodev commented Jan 16, 2013

Result is

2013-01-16 11:38:12.746 Untitled[3888:707] B, Y
2013-01-16 11:38:12.748 Untitled[3888:707] A, Y

@janodev
Copy link
Author

janodev commented Jan 16, 2013

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.

Copy link

ghost commented Jan 16, 2013

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.

@janodev
Copy link
Author

janodev commented Jan 16, 2013

Thank you, that clears it up. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment