类扩展中属性的可见性和目标C中的继承 [英] Visibility of properties in Class Extensions and inheritance in Objective C

查看:83
本文介绍了类扩展中属性的可见性和目标C中的继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有2个类:Money和Dollar,其中Dollar继承自Money。

Say I have 2 classes: Money and Dollar, where Dollar inherits from Money.

Money具有在类扩展中声明的属性:

Money has a property declared in a class extension:

#import "Money.h"

@interface Money ()
@property(nonatomic) NSUInteger amount;
@end

@implementation Money

@end

美元继承了此属性,但是从Dollar的方法中看不到该属性。我可以通过在Dollar.m中重新声明属性来修复:

Dollar inherits this property, but it's not visible from methods in Dollar. I can "fix", by redeclaring the property in Dollar.m:

@interface Dollar ()
@property(nonatomic) NSUInteger amount;
@end
@implementation Dollar


}
@end

我真的不喜欢这个,甚至不确定我是否知道编译器在做什么:

I really dislike this and I'm not even sure that I know what the compiler is doing:


  1. 是否只是使该属性可见?

  2. 是否正在创建新属性和新iVar并屏蔽先前的属性?

除了该类及其子类的实现之外,对所有人隐藏属性的最佳方法是什么?

What's the best way to have a property hidden from everyone except the implementation of the class and its subclasses?

理想情况下,我不希望在.h文件中看到金额,因为这是一个实现细节。

Ideally, I would not like amount to be visible in the .h file, as it's an implementation detail.

推荐答案

第一个答案问题,可能是第一个选择。它只是在编译时以 Money 欺骗所有内容。编译器和预编译器都很聪明。

In answer to the first question, probably the first option. Its just smooshing everything together for Money at compile time. Compilers and Pre-Compilers are clever.

您可以使用私有标头来完成您要执行的操作

You can use private headers to accomplish what you are trying to do

公共头文件 Money.h

//Money.h 
@interface Money : NSObject
//public decl 
@end

子类 Money-Private.h

//Money-Private.h
@interface Money ()
@property(nonatomic) NSUInteger amount;
@end

Money 以及任何子类或类别,例如

Which is used by the implementation of Money and any subclasses or categories e.g

美元 Dollar.h

#import "Money.h"
@interface Dollar:Money
@end

和实现 Dollar.m

#import "Money-Private.h"
@implementation Dollar

-(void)foo
{
    self.amount = 75;
}

@end

您是否应该选择创建一个公共框架,然后确保仅将公共标头复制到捆绑包中。

Should you ever choose to create a public framework then make sure only the public headers get copied into the bundle.

这篇关于类扩展中属性的可见性和目标C中的继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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