Why is there another @interface inside the.m file?

2020-02-13 07:26发布

问题:

Sometimes I see another interface declaration like this:

@interface MyCode ()

@end

Isn't this duplicating the one in the .h file?

回答1:

That is a category provided by Xcode and is used to declare private properties and methods that are only usable from within this implementation file.

You won't always want to expose all of the methods from your class to the outside world, and instead you would declare them in this private category (I always prefix these private methods with an underscore (_) to make it obvious I am calling a private method, but that is entirely optional).

As an example, here is a private intialization method that I don't want exposed:

@interface MyClass ()

- (BOOL)_init;

@end

@implementation MyClass

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self != nil)
    {
        if (![self _init])
            self = nil;
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:code];
    if (self != nil)
    {
        if (![self _init])
            self = nil;
    }
    return self;
}

- (BOOL)_init
{
     self.something = whatnot;
     self.thingA = self.thingB;
     return YES;
}


回答2:

it is used when you want to declare private ivars/properties/methods.



回答3:

In .h file you've got public methods and properties, and in .m file you have private.



回答4:

The concept is that you can make your project much cleaner if you limit the .h to the public interfaces of your class, and then put private implementation details in this class extension. See the discussion of private class extensions in the Programming with Objective-C guide.



回答5:

This @Interface allows you to declare private ivars, properties and methods. So anything you declare here cannot be accessed from outside this class. In general, you want to declare all ivars, properties and methods by default as private (in this @interface()) unless an instance of the class needs to access them.

Hope this helps



回答6:

It's a class extension. Read more

Usually used for declaration private ivars/properties/methods.