user590849
user590849

Reputation: 11785

Cannot understand the following code in objective C?

Please refer to the following code:

Filename: myclass.h

@interface myclass:NSObject
...
@end
@interface NSObject(CategoryName)
....
@end

I do not understand how can we declare 2 @interface directives in the same .h file? and like in the implementation file we can only implement one of the above interfaces.eg.

Filename: myclass.m

@implementation myclass
...
@end 

in the above code, i cannot write @implementation Categoryname as the name of the .h file is myclass. How do i implement the methods described in the category.

Also can my main interface extend one class and the category that i am defining in the same .h file extend another class?

How can i declare one class into another class (nested class) in objective c?

thank you in advance.

UPDATE

After reading the responses, i have 2 more questions

  1. if i have 2 @interface in my .h file, can i have 2 @implementation in the .m file.
  2. if i have 2 @interface in my .h file and if i import that .h file in another file, can i access the methods under both the @interface directives?
  3. Can i implement the methods declared in the category in the interface of another class?

Upvotes: 0

Views: 103

Answers (1)

Abizern
Abizern

Reputation: 150755

Add it as another declaration in the same file, like this

@implementation NSObject (categoryname)

...

@end

It's all described in the Categories and extensions section of the Developer docs.

Since you are extending a different class in the same interface - you need to have a separate declaration in the implementation file.

Edited to answer the additions:

  1. Yes - I just said so.
  2. Yes - Interfaces expose public methods.
  3. Somewhere in your compilation tree, you have to have a file that implements the methods that you declared in your category. Most people define categories in their own files with a particular naming convention.For example uliwitness/uikit. For your example it would be in NSObject+CategoryName.h and NSObject+CategoryName.m. Once you have declared and defined a category on a class it is available to all objects of that class. So since you are adding an extension to NSObject, those methods are available to all classes that inherit from NSObject (which is practically all classes) whether or not you import the header file. But, you get a compiler warning if you don't import the header, even though the Objective-C runtime will still allow those methods to be called.

Upvotes: 4

Related Questions