Accessing variables of another class in xcode

前端 未结 5 407
一向
一向 2021-01-24 11:52

I have a balloonGameViewController.h and another class I made called balloon.h

I want to access some variables I set in balloon.h

相关标签:
5条回答
  • 2021-01-24 12:34

    Just import the balloon.h file into your balloonGameViewController

    #import balloon.h
    

    and then access the variables as usual, assuming they are public. Otherwise you have to make them public or create getters and setters.

    0 讨论(0)
  • 2021-01-24 12:37

    As others said, you'll have to #import baloon.h. But you did not say if these variables are global variables or ivars of a class. If they are ivars, you'll first have to find the instance of the class (the object) of which they are ivars. If you have that, and they are public or properties, you can access them as members of that object.

    IOW, it is hard to tell if you don't tell us what kind of variables in balloon.h you want to access. But, see above.

    0 讨论(0)
  • 2021-01-24 12:43

    i don't know if i got your question well, but i faced that once upon a time , i couldn't access the variables via (.) operator but via (->)

    in my case there were 2 classes : MenuCalss , and ToolsClass ;

    in ToolsClass.h :
    @public
        bool ToolBarVisible;
    

    //in MenuCalss there was a ToolsClassObject. ToolsClassObject is an instance of type ToolsClass, which can be created by importing the ToolsClass.h and initializing a new instance.

    , and the access way in MenuClass.m is :

    ToolsClassObject->ToolBarVisible = false;
    
    0 讨论(0)
  • 2021-01-24 12:49

    How are your variables set in ballon.h? You should use @property to declare variables that you want other classes to be able to access. Then, you can access them either by treating them as a method, or dot notation:

    myObject.variable;
    

    myObject should be an instance of type balloon, which can be created by importing the balloon.h and initializing a new instance, if you do not already have one.

    0 讨论(0)
  • 2021-01-24 12:53

    Using your XCode you need to make import, declare the property, and then use "object.variable" syntax. The file "balloonGameViewController.m" would look in the following way:

    #import balloonGameViewController.h
    #import balloon.h;
    
    @interface balloonGameViewController ()
    ...
    @property (nonatomic, strong) balloon *objectBalloon;
    ...
    @end
    
    @implementation balloonGameViewController
    
    //accessing the variable from balloon.h
    ...objectBalloon.variableFromBalloon...;
    
    ...
    @end
    
    0 讨论(0)
提交回复
热议问题