Reputation: 762
I'm trying to call a method from another class with a simple button in my storyboard. Here are my files:
ViewController.m
// ViewController.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "PrintHello.h"
@interface ViewController : UIViewController <NSObject>{
PrintHello *printMessage;
}
@property (nonatomic, retain) PrintHello *printMessage;
@end
ViewController.m
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize printMessage;
- (void)viewDidLoad{
[super viewDidLoad];
NSLog(@"ViewDidLoad loaded");
}
- (IBAction)Button01:(id)sender{
self.printMessage = [[PrintHello alloc] init]; // EDIT: THIS LINE WAS MISSING NOW IT WORKS
[self.printMessage Print];
NSLog(@"Button01 Pressed");
}
@end
PrintHello.h
// PrintHello.h
#import <Foundation/Foundation.h>
@interface PrintHello : NSObject
-(void) Print;
@end
PrintHello.m
// PrintHello.m
#import "PrintHello.h"
@implementation PrintHello
-(void)Print{ NSLog(@"Printed");}
@end
And also in the storyBoard there is a Button01 linked to the Viecontroller. From the Log i know that:
viewDidLoad is loaded and the button is pressed when is pressed :) BUT the method Print is not called?
Where am i doing wrong?
Upvotes: 0
Views: 5573
Reputation: 1915
As woz has said, you haven't initialized printMessage yet, so the object doesn't exist yet! You probably want to initialize it within viewDidLoad of your ViewController.m file, rather than reinitialize the object over and over again within the button click.
-(void)viewDidLoad
{
[super viewDidLoad];
self.printMessage = [[PrintHello alloc] init];
NSLog(@"ViewDidLoad loaded");
}
Upvotes: 0
Reputation: 10994
Before you call [self.printMessage Print];
, I think you need to put self.printMessage = [[PrintHello alloc] init];
.
Upvotes: 1