I am just want to know if there is any difference between:
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property ...
@end
in the *.h file and:
@interface AppDelegate()
@property ...
@end
@implementation AppDelegate
in the *.m file.
When do I need prefer the first version and when it will be better to use second version ?
Anything you can put in a .h file you can put in a .m file. The contents of an imported .h are directly copied into the .m during the early stages of compilation, so there is no syntactic difference based on where a statement is placed.
But you will note that there is a difference in syntax between
@interface AppDelegate : NSObject <NSApplicationDelegate>
and
@interface AppDelegate()
The second form is an extension of the already-described interface, vs being a new (and conflicting) version. The fact that it is placed in the .m (which is not required -- it could be placed in the .h without raising an error) means that any other module importing the .h will not "see" it, making it "private" (as much as anything in Objective-C is private).
Basically, the .h file is your public header, and your .m file is your implementation (private).
Whatever you put in your @interface
in your .m will be private (class extensions and what not), and your @interface
in your .h is public.
If I was going to pass stuff to the UIViewController using a segue, or if I needed access to the data in some object I would put my @properties
in my .h. Otherwise I just put everything in the private class extension (.m). You could get away with only using your @properties
in the .h file though.
Generally speaking you use the @interface
in the header file (.h) to declare public properties and methods, which are visible to other classes that import this class.
The @interface
in you implementation file (.m) is used to declare private properties and methods, which are only visible within that class, and cannot be used or accessed by other classes in your project.
The code:
@interface AppDelegate()
@property ...
@end
Creates a private class extension which cannot be seen from outside the class implementation file, making it private, as opposed to those in the header file which are public.
It's still possible to call the private property from other classes, once you have suppressed the compiler warnings, given the dynamic nature of Objective-C.
It's also useful for declaring private methods, which I prefix with _
to differentiate them from public methods, although there is no requirement to do that.
@interface AppDelegate()
- (BOOL)_doCoolThing;
@end
You don't even have to declare the private methods, given the compiler will work fine with just the definition, however I always do both declare and define them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With