为什么.m 文件中还有另一个@interface? [英] Why is there another @interface inside the.m file?

查看:77
本文介绍了为什么.m 文件中还有另一个@interface?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我会看到另一个这样的接口声明:

Sometimes I see another interface declaration like this:

@interface MyCode ()

@end

这不是在复制 .h 文件中的那个吗?

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

推荐答案

这是 Xcode 提供的一个类别,用于声明只能在此实现文件中使用的私有属性和方法.

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;
}

这篇关于为什么.m 文件中还有另一个@interface?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆