从外部类访问私有变量

编程入门 行业动态 更新时间:2024-10-27 19:28:28
从外部类访问私有变量 - iOS(Accessing private variables from an external class - 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?

最满意答案

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

但是,有办法规避这种限制。

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

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

[object valueForKey:@"variable_name"];

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"];

更多推荐

本文发布于:2023-07-31 08:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1341947.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!