How can I access variables from another class?

后端 未结 4 1536
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 02:37

There is probably a very simple solution for this but I can\'t get it working.

I have got multiple classes in my Cocoa file. In one of the classes class1

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-06 03:15

    You can either make the variable public, or make it into a property. For example, to make it public:

    @interface Class1
    {
    @public
        int var;
    }
    // methods...
    @end
    
    // Inside a Class2 method:
    Class1 *obj = ...;
    obj->var = 3;
    

    To make it a property:

    @interface Class1
    {
        int var;  // @protected by default
    }
    @property (readwrite, nonatomic) int var;
    // methods...
    @end
    
    @implementation Class1
    @synthesize var;
    ...
    @end
    
    // Inside a Class2 method:
    Class1 *obj = ...;
    obj.var = 3;  // implicitly calls [obj setVar:3]
    int x = obj.var;  // implicitly calls x = [obj var];
    

提交回复
热议问题