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;
有帮助吗?

解决方案

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.

其他提示

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.

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 ;)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top