How can I access variables from another class?

后端 未结 4 1538
没有蜡笔的小新
没有蜡笔的小新 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:18

    try making a file that holds your variables that need to be accessed throughout the app.

    extern NSString *stringVariable;
    
    @interface GlobalVariables
    
    @property (retain, nonatomic) NSString *stringVariable;    
    
    @end
    

    and in the GlobalVariables.m file add

    #import "GlobalVariables.h"
    
    @implements GlobalVariables
    
    @synthesize stringVariable;
    
    NSString *stringVariable;
    
    @end
    

    And then as long as you import GlobalVariables.h into which ever .m files you need to access that variable in you can assign and access anywhere throughout your program.

    EDIT

    My answer that I have given above is differently not the way I would go about doing this now. It would be more like

    @interface MyClass
    
    @property (nonatomic, strong) NSString *myVariable;
    
    @end
    

    then in the .m file

    @implementation MyClass
    
    @sythesize = myVariable = _myVariable; // Not that we need to do this anymore
    
    @end
    

    Then in another class in some method I would have

    // .....
    MyClass *myClass = [[MyClass alloc] init];
    [myClass setMyVariable:@"My String to go in my variable"];
    // .....
    

提交回复
热议问题