我正在通过读书来学习c语言。当我阅读有关类扩展的章节时,这本书给出了以下示例代码:

// A class extension
@interface BNREmployee ()

@property (nonatomic) unsigned int officeAlarmCode;

@end

@implementation BNREmployee
...
@end

该书说,不是BNREmployee实例的对象无法再看到此属性 officeAlarmCode。举个例子:
BNREmployee *mikey = [[BNREmployee alloc] init];
unsigned int mikeysCode = mikey.officeAlarmCode;

这种尝试将导致编译器错误,显示为“没有可见的@interface声明实例方法officeAlarmCode”。

但是我很困惑。我的意思是我觉得这本书的文字及其示例代码相互矛盾。书中说,不是BNREmployee实例的对象不能再看到officeAlarmCode属性。但是在上面的示例代码中,mikey不是BNREmployee的实例吗?为什么它看不到officeAlarmCode事件,它是BNREmployee的实例?

===更新=====

我正在读的书是this one。第22章,第162页。

我只是想验证这本书的解释是否具有误导性,我正在这里寻找清晰的解释。因为书说“对象是而不是实例的不再可以看到属性officeAlarmCode”,对于像我这样的书读者来说,我觉得它暗示了作为BNREmployee实例的对象可以看到属性BNREmployee。这就是我感到困惑的原因,因为officeAlarmCodemikey的实例,但是它无法访问officeAlarmCode。

最佳答案

按照Apple Docs
1.类扩展可以将自己的属性和实例变量添加到类中
2.类扩展通常用于扩展具有其他 private 方法或属性的 public 接口,以便在类本身的实现中使用。

因此,如果您在类扩展中声明该属性,则该属性仅对实现文件可见。喜欢

BNREmployee.m

@interface BNREmployee ()

@property (nonatomic) unsigned int officeAlarmCode;

@end

@implementation BNREmployee

- (void) someMethod {
    //officeAlarmCode will be available inside implementation block to use
     _officeAlarmCode = 10;
}
@end

如果要在其他类中使用officeAlarmCode,例如,OtherEmployee类,则需要在BNREmployee.h文件中创建具有readOnly或readWrite访问权限的officeAlarmCode属性。然后你可以像
BNREmployee.h

@property (nonatomic, readOnly) unsigned int officeAlarmCode; //readOnly you can just read not write

OtherEmployee.m
import "BNREmployee.h"
@interface OtherEmployee ()

@property (nonatomic) unsigned int otherAlarmCode;

@end

@implementation OtherEmployee

您可以创建BNREmployee实例,并可以将officeAlarmCode值分配给otherAlarmCode属性,如下所示
BNREmployee *bnrEmployee = [BNREmployee alloc] init];
_otherAlarmCode = bnrEmployee.officeAlarmCode;

关于ios - Objective-C中的类扩展,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27963551/

10-12 04:29