user2002708
user2002708

Reputation: 103

Variables declared inside and outside brackets of @interface

Why do you have to declare variables inside the @interface brackets like this?

@interface myClass : UIViewController {
     NSString *myString;
     IBOutlet UILabel *myLabel;
}

Why not just do it here?

@interface myClass : UIViewController {
     IBOutlet UILabel *myLabel;
}

NSString *myString;

Upvotes: 2

Views: 2455

Answers (3)

ppalancica
ppalancica

Reputation: 4277

The way we are supposed to do that is like bellow:

@interface MyClass : UIViewController {

}

@property (strong, nonatomic) NSString *myString;

@property (weak, nonatomic) IBOutlet UILabel *myLabel;

@end

Just follow the conventions and do not complicate your developer's life ;)

Upvotes: 0

rmaddy
rmaddy

Reputation: 318824

Because the first form is correct Objective-C syntax for declaring instance variables. The second form doesn't define an instance variable, it defines a global. If you wish to define a global, define it before the @interface block so it's doesn't appear to be part of the class definition.

Outside the curly braces is the place for method and property declarations.

But better yet, private ivars should be declared in the .m file, not the .h file.

@implementation myClass {
    // private ivars here
}

I don't think this applies to IBOutlet though. I think they need to be in the .h file. But I don't use IB so I don't know for sure.

Upvotes: 1

user529758
user529758

Reputation:

Because if you don't, then the variable will be a file-scope variable (with static storage duration) and it won't be an instance variable of your class.

Upvotes: 6

Related Questions