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

2020-02-13 06:47发布

Sometimes I see another interface declaration like this:

@interface MyCode ()

@end

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

6条回答
贪生不怕死
2楼-- · 2020-02-13 07:17

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

查看更多
家丑人穷心不美
3楼-- · 2020-02-13 07:18

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

查看更多
家丑人穷心不美
4楼-- · 2020-02-13 07:23

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

查看更多
女痞
5楼-- · 2020-02-13 07:29

It's a class extension. Read more

Usually used for declaration private ivars/properties/methods.

查看更多
ゆ 、 Hurt°
6楼-- · 2020-02-13 07:30

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;
}
查看更多
\"骚年 ilove
7楼-- · 2020-02-13 07:38

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.

查看更多
登录 后发表回答