目标C - 隐藏iVars [英] Objective C - Make iVars hidden

查看:95
本文介绍了目标C - 隐藏iVars的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题。



假设我有一个名为WebServiceBase.h的类。我需要在该类中添加一个名为NSString * requestData的iVar。但是我不需要将iVar添加到头文件中并使其对外部人员可见。 (如果我将其作为类库分发)



此外,我还需要能够在从WebServiceBase扩展的其他类中访问此requestData iVar。 H。 (这些扩展类是由我编写的。不是来自外部人员)



我尝试在类扩展中声明requestData iVar。但是扩展类不可见。



任何解决方案?我需要保护我的数据并使其隐藏在外部世界。

解决方案

您可以通过<

将您的ivars定义为受保护code> @protected 关键字,这意味着您的类和所有子类可以毫无问题地访问它,但是编译器不会允许这个用于其他不从您的基类继承的类:

  @interface Foo:NSObject 
{
@protected
NSObject * a;
}

它就这么简单,已经为您提供了所有可以获得的安全保障Objective-C。


Here's my question.

Let's say I have a class called WebServiceBase.h. And I need to add a iVar in to that class called NSString *requestData. But I don't need to add that iVar in to the header file and make it visible to the external people. (If I'm distributing this as a class library)

Also I need to be able to access this requestData iVar, within the other classes that is extended from the WebServiceBase.h. (These extended classes are written by me. Not from the external people)

I tried with declaring the requestData iVar within the class extensions. But then it's not visible to the extended classes.

Any solution for this? I need to protect my data and make it hide from the external world.

解决方案

You can define your ivars as protected via the @protected keyword, meaning that your class and all subclasses can access it without any problem, but the compiler won't allow this for other classes which don't inherit from your base class:

@interface Foo : NSObject
{
@protected
    NSObject *a;
}

Its as simple as that and already gives you all the safety you can get from Objective-C.

这篇关于目标C - 隐藏iVars的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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