Obj-C Sending Messages Between Classes
I'm a newbie in iPhone Programming. I'm trying to send a message from one view controller to another. The idea is that viewControllerA takes information from the user and sends it to viewControllerB. viewControllerB is then supposed to display the information in a label.
viewControllerA.h
#import <UIKit/UIKit.h>
@interface viewControllerA : UIViewController
{
int num;
}
-(IBAction)do;
@end
viewControllerA.m
#import "viewControllerA.h"
#import "viewControllerB.h"
@implementation viewControllerA
- (IBAction)do {
//initializing int for example
num = 2;
viewControllerB *viewB = [[viewControllerB alloc] init];
[viewB display:num];
[viewB release];
//viewA is presented as a ModalViewController, so it dismisses itself to return to the
//original view, i know it is not efficient
[self dismissModalViewControllerAnimated:YES];
}
- (void)dealloc {
[super dealloc];
}
@end
viewControllerB.h
#import <UIKit/UIKit.h>
@interface viewControllerB : UIViewController
{
IBOutlet UILabel *label;
}
- (IBAction)openA;
- (void)display:(NSInteger)myNum;
@end
viewControllerB.m
#import "viewControllerB.h"
#import "viewControllerA.h"
@implementation viewControllerB
- (IBAction)openA {
//presents viewControllerA when a button is pressed
viewControllerA *viewA = [[viewControllerA alloc] init];
[self presentModalViewController:viewA animated:YES];
}
- (void)display:(NSInteger)myNum {
NSLog(@"YES");
[label setText:[NSString stringWithFormat:@"%d", myNum]];
}
@end
开发者_开发问答
YES is logged successfully, but the label's text does not change. I have made sure that all of my connections in Interface Builder are correct, in fact there are other (IBAction) methods in my program that change the text of this very label, and all of those other methods work perfectly...
Any ideas, guys? You don't need to give me a full solution, any bits of information will help. Thanks.
With
viewControllerB *viewB = [[viewControllerB alloc] init];
you are instantiating a new viewControllerB
. This is not the viewControllerB
that (I presume) you have in your nib file. You should make an outlet for that and wire it up.
Otherwise, possibly instantiate it with [... initWithNibName:]
from a nib, instead of just [... init]
, and then (either way) push the instantiated view controller using [self.navigationController pushViewController:viewB animated:YES]
, or by presenting it modally as you seem to have mastered already.
As a sidenote, maybe name the viewcontroller variable viewConB
, since there is a clear and important distinction between views and view controllers. Furthermore, class names tend to start with upper case, and variables with lower case, to keep things clear.
精彩评论