In my mainViewController.h I have declared a UIButton *myButton and I synthesize it in mainViewController.m. I also created an accessor method (myButton) that just returns the button. In another view (and therefore a different view controller class) I have:
mainViewController *mainVC = [[mainViewController alloc] init];
UIButton *myButton = [mainVC myButton];
[eventButton setTitle:@"New Title" forState:UIControlStateNormal];
I want this code to change the title label of the button, but it doesn’t seem to work. Using a NSLog statement (NSLog(@"%@", myButton.titleLabel);) to see what the current title is, it always returns null. From what I’ve read, this is because I’m creating an instance of the mainViewController and therefore I’m not actually accessing/changing the button. How can I access the actual view controller and not an instance?
(Before the longer discussion: it looks like you’re typing
myButtonone line 2, andeventButtonon line 3. Make sure these match!)You’re correct in thinking that you’re creating a new instance of
mainViewController. To get at the one you want, You’ll either need to pass a reference tomainViewControllerinto the new view controller when you create it, writing a method like:to override
init, or, if you’ve got a reference tomainViewControllerin your App Delegate, you can get it using:Either way you choose, you’ll want to read up on object oriented programming and pointers in objective C. When you call
alloc, you’re manufacturing a new copy of that class. All copies sit in different chunks of memory, so any new one you make (as in your code above) is actually a totally different entity, like two Priuses, or something like that.A pointer is like a nametag that identifies, or points the way, to that block of memory. In my
initcode example above, we’re attaching a new nametag to amainViewControllerinstance with the same guts. Same thing with the second line — we make a new pointer (see the star?) tell it it’s going to be pointing to aMainViewControllerinstance, and slap that nametag, or pointer, on to an instance.(The second one is a little more complicated, as you’re plucking
mainViewControllerfrom an object called a singleton, or an object that you can get at from anywhere… read more about those and the App Delegate at this post from Cocoa with Love.)Anyway, I get nervous expounding on this stuff on Stack! Check out Apple’s Objective C reference for some more of the basics. The sample code on the iOS Dev Center is really, really good to check out. Download a project that looks nice, or, better yet, just create a project from an Xcode template, and go try to figure out how it’s stitched together. Good luck!