如何从其他类更改实例变量属性

时间:2012-08-27 17:35:18

标签: objective-c properties instance-variables

如果我在一个班级中有一个标签并且想要更改它显示的文本,我怎么能从另一个班级开始?

2 个答案:

答案 0 :(得分:1)

在objective-c中,您有properties来有效地自动创建用于访问实例变量的getter和setter。

@interface MyClass
{
    UILabel *instanceLabel; //Not required, but I find it can make it clearer
}

@property (nonatomic, retain) UILabel *instanceLabel;

@end



@implementation MyClass

@synthesize instanceLabel; //Not required as of XCode 4.4
@end

然后从您的其他类中使用点运算符访问这些属性的简单情况。

myClassInstance.instanceLabel.text = @"newText";

您不必使用点运算符:

[myClassInstance instanceVariable].text = @"newText";

答案 1 :(得分:-1)

通常一个人使用set-functions。

即。伪代码:

class YourClass 
{
    private var str;

    public YourClass(var str)
    {
        this.str = str;
    }

    public setString(var str)
    {
        this.str = str;
    }

}




class SecondClass 
{
    private final YourClass myInstance;

    public SecondClass(final YourClass myInstance)
    {
        this.myInstance = myInstance;
    }

    public performChange()
    {
        myInstance.setString("hello");
    }
}

然后调用SecondClass :: performChange()会将“YourClass myInstance”的实例变量更改为“hello”。