CLL
CLL

Reputation: 331

Difference in variable declarations - objective c

My question is mostly conceptual - what exactly is the difference between the following two snippets of code?

1)

@implementation Person 
{    
NSString *name;
// other variables
} 

- (void) someMethod

@end

2)

@implementation Person

NSString *name;
//other variables

- (void) someMethod

@end

The reason I ask is I was able to compile some code that followed format #2 but not format #1, and I was curious as to the difference between the two.

Upvotes: 0

Views: 25

Answers (2)

Francesco
Francesco

Reputation: 1848

If I'm not wrong, with the second format you are declaring a global (for the compilation unit) variable (the missing * is a typo or is it "real"?).

About the first format: depending on the objective-c versions it can be correct or wrong. Previous versions (for example in OS X 10.5) required attribute definitions in the @intereface

@interface Person 
{    
NSString *name;
// other stuff
} 

- (void) someMethod

@end

Which is an attribute definition for the class Person, while now this requirement is "relaxed", and attributes can also be declared in the implementation block (but you have to use the {})

Upvotes: 1

Eiko
Eiko

Reputation: 25632

The first declares an instance variable. That name belongs to the Person object.

The second would declare a global variable.

Upvotes: 1

Related Questions