Accessing a value of a class's variable from another - objective-c

前端 未结 2 665
别那么骄傲
别那么骄傲 2021-01-15 11:26

This is probably a silly question but I\'m having a hard time trying to solve it. The thing is that a have a class that implements a counter and at the end of it procedures

相关标签:
2条回答
  • 2021-01-15 12:17

    In your header file you declare your iVar as

    {
        int movesCounter;
    }
    

    but you synthesize the property with

    @synthesize movesCounter = _movesCounter; // note the underscore
    

    so the movesCounter iVar does not get connected to the movesCounter property. If you are updating just movesCounter instead of self.movesCounter or _movesCounter then external classes will not be able to see these changes.

    0 讨论(0)
  • 2021-01-15 12:21

    Your problem is that you're creating a new instance of Class1 in your Class2 init method:

    Class1 *theClass1 = [[Class1 alloc] init];
    

    This new instance is in addition to the one with the int you've been incrementing successfully, and as it's a fresh slice of memory, its value for movesCounter is still 0. What you really want is a pointer to the specific copy of Class1 that you've been working with -- no alloc / init needed or desired. Try making a property in Class2 that can hold your pointer to Class1:

    #import "Class1.h"
    
    @interface Class2 : NSObject {
        Class1 *myPointerToClass1;
    }
    @property (nonatomic, retain) Class1 *myPointerToClass1;
    

    And of course @synthesize myPointerToClass1 in the .m of Class2. Now that Class2 is ready to hold a pointer to Class1, you need simply to populate it. In Class1, after the code that alloc's and init's the Class2 instance, use code like this:

    myClass2.myPointerToClass1 = self;
    

    Just to make sure I haven't forgotten anything I did all this using your code above and everything worked just fine for me.


    EDIT: original answer begins here, but is now irrelevant..... You mention having defined the counter as a property, but have you also synthesized the instance variable in your implementation (.m) file?

    @synthesize myCounter;
    

    This will create the setter and getter methods automatically for you. Also, have you verified that the value is being incremented at all, perhaps with an NSLog statement in the viewcontroller?

    NSLog(@"myCounter is currently equal to %d", myCounter); // assuming an int
    

    If these basics are covered, maybe you could edit your question to include the code showing us more about how the misbehaving class is getting this pointer to the variable in the first place.

    0 讨论(0)
提交回复
热议问题