8

Possible Duplicate:
Difference between @interface definition in .h and .m file
What is the @interface declaration in .m files used for in iOS 5 projects?

I've seen code like this:

// In Header.h
@interface Header{}
@end

// In Header.m
@interface Header()
@end

My questions are:

  1. What's the difference in putting it in 2 files?
  2. Why put {} after class name in ".h" file and why "()" in ".m" file?
Community
  • 1
  • 1
itsaboutcode
  • 24,525
  • 45
  • 110
  • 156

2 Answers2

12
@interface MyClass(){
    NSInteger aInt;

}
@property(nonatomic,strong) NSString *name;
@end

is a class extension

with modern compilers this is a great way, to decrale methods, ivars and properties only for private use in the class MyClass.

Class extensions have to be declared in the main implementation file (not in a category).

So you can hide implementation details from the header file, they are private.

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
  • thanks, really solved the big puzzle for me. – itsaboutcode Mar 22 '12 at 17:42
  • 1
    You can also create implementation properties, which I find are more useful than class extensions. – Richard J. Ross III Mar 22 '12 at 17:44
  • To use ivars in extensions, you have to use the llvm 3+. GCC is not aware of this syntax – vikingosegundo Mar 22 '12 at 17:45
  • @RichardJ.RossIII - what's implementation properties thing? One more thing, I have seen code doing this, interface Header{} property(nonatomic,readonly) BOOL sessionDidExpire; end and then in the .m file, property (nonatomic,readwrite) BOOL sessionDidExpire; what's this thing? – itsaboutcode Mar 22 '12 at 17:47
  • indeed with LLVM it is true, you can declare ivars at `@implementation MyClass { NSInteger aInt;}` to. but I like to separate it into a class extension. – vikingosegundo Mar 22 '12 at 17:48
  • @itsaboutcode excuse me, I mean implementation iVars, however, I use ARC so much there really isn't much difference between the two now. – Richard J. Ross III Mar 22 '12 at 17:48
  • 1
    it is a public readonly property, while from inside the class u can also write to it — very handy. – vikingosegundo Mar 22 '12 at 17:49
3

This has become a common practice for declaring "private" properties/methods for a given class. By declaring them in an anonymous class extension inside the .m, these properties/methods are not exposed to consuming objects.

Ian L
  • 5,553
  • 1
  • 22
  • 37