从外部类访问私有变量 - iOS [英] Accessing private variables from an external class - iOS

查看:116
本文介绍了从外部类访问私有变量 - iOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在类中有一个私有变量,我试图从外部类访问该变量。
有没有办法可以做到这一点?

I have a private variable in a class and I am trying to access that variable from an external class. Is there a way I could do this?

推荐答案

私有实例变量根据定义是私有的。您无法从外部访问它们。如果您是该类的作者,则应为该变量提供访问器方法。如果你不是,你应该避免访问变量。

The private instance variables are, by definition, private. You cannot access them externally. If you are the author of the class, you should provide accessor methods for the variable. If you're not, you should refrain from accessing the variable.

然而,有办法规避这个限制。

However, there are ways to circumvent that limitation.

您可以在第一个类上创建一个类别,并为实例变量添加一个访问器方法。

You may create a category on the first class and add an accessor method for the instance variable.

或者您可以使用键值编码来访问变量。

Or your may use Key-Value Coding to access the variable.

[object valueForKey:@"variable_name"];

这篇关于从外部类访问私有变量 - iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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