How to make and use first object in Objective C to store sender tag
- by dbonneville
I started with a sample program that simply sets up a UIView with some buttons on it. Works great.
I want to access the sender tag from each button and save it. My first thought was to save it to a global variable but I couldn't get it to work right.
I thought the best way would be to create an object with one property and synthesize it so I can get or set it as needed.
First, I created GlobalGem.h:
#import <Foundation/Foundation.h>
@interface GlobalGem : NSObject {
int gemTag;
}
@property int gemTag;
-(void) print;
@end
Then I created GlobalGem.m:
#import "GlobalGem.h"
@implementation GlobalGem
@synthesize gemTag;
-(void) print {
NSLog(@"gemTag value is %i", gemTag);
}
@end
The sample code I worked from doesn't do anything I can see in "main" where the program initializes. They just have their methods and are set up to handle IBOutlet actions.
I want to use this object in the IBOutlet methods. But I don't know where to create the object.
In the viewDidLoad, I tried this:
GlobalGem *aGem = [[GlobalGem alloc]init];
[aGem print];
I added reference to the .h file of course. The print method works. In the nslog I get "gemTag value is 0".
But now I want to use the instance aGem in some of the IBOutlet actions. For instance, if I put this same method in one of the outlet actions like this:
- (IBAction)touchButton:(id)sender {
[aGem print];
}
...I get a build error saying that "aGem is undeclared".
Yes, I'm new to objective c and am very confused.
Is the instance I created, aGem, in the viewDidLoad not accessible outside of that method?
How would I create an instance of a Class that I can store a variable value that any of the IBOutlet methods can access?
All the buttons need to be able to store their sender tag in the instance aGem and I'm stuck.
As I mentioned earlier, I was able to write the sender tag to a global variable I declared in the UIView .h file that came with the program, but I ran into issues using it.
Where am I off?