6

I've noticed a variety of @interface declarations for Objective-c classes. I'd like to understand why developers declare @interface in the following ways:

// in the .h file
@interface MyClass : NSObject
// ...
@end

// in the .m file (what's the purpose of the parens?)
@interface MyClass ()
// more property declarations which seem like they can go in the .h file
@end

// again in the .m file (what's the purpose of private?)
@interface MyClass (Private)
// some method declarations
@end
SundayMonday
  • 19,147
  • 29
  • 100
  • 154
  • 1
    For example: [a quick search](http://stackoverflow.com/search?q=%5Bobjc%5D+%40interface+parentheses&submit=search) turns up http://stackoverflow.com/questions/7378479/what-does-the-text-inside-parentheses-in-interface-and-implementation-directive – jscs Oct 12 '11 at 18:53
  • 1
    What about looking at the [language spec](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocDefiningClasses.html#//apple_ref/doc/uid/TP30001163-CH12-SW1)? – jscs Oct 12 '11 at 19:00

3 Answers3

6

This is just a normal class interface, inheriting from NSObject, where you declare ivars, properties and methods

// in the .h file
@interface MyClass : NSObject
// ...
@end

The following two are categories, which allow you to add methods to a class. It is not a subclass however (do not declare a method with the same name, as you won't be able to access the original one). If you have a named category of the interface (like @interface MyClass (Private)), then the implementation should be provided in @implementation MyClass (Private), in the case of unnamed categories (also called extensions), the implementation can be provided as usual. Note that extensions also allow you to add ivars to the class while (named) categories do not.

// in the .m file (what's the purpose of the parens?)
@interface MyClass ()
// more property declarations which seem like they can go in the .h file
@end

// again in the .m file (what's the purpose of private?)
@interface MyClass (Private)
// some method declarations
@end
jbat100
  • 16,757
  • 4
  • 45
  • 70
  • 1
    It's possible _currently_ to add storage to a class in an extension. It is unlikely to ever be possible to do so via a category. – jscs Oct 12 '11 at 18:57
2

It is used to declared private methods.

This response explain this in details: What are best practices that you use when writing Objective-C and Cocoa?

Community
  • 1
  • 1
M to the K
  • 1,576
  • 3
  • 17
  • 27
0

What ever goes in the .m file is private. the parens are for categories so you can segment your code into categories to make it more readable. because the code is in .m and private, they called the category Private.

Daniel
  • 30,896
  • 18
  • 85
  • 139