Reputation: 6824
I know this insanely simple, but I am re-teaching myself the basics and trying to get my head around this:-)
I have one ViewController called MainVC and I have one called ClassVC
In ClassVC I have this code:
@interface ClassVC : UIViewController
{
NSString *mainLine;
}
@property (nonatomic, retain) NSString *mainLine;
@end
and I have this in the implementation file:
@synthesize mainLine = _mainLine;
-(NSString *)_mainLine
{
_mainLine = @"This a string from a Class";
return _mainLine;
}
Now I was thinking that if I #import the ClassVC into MainVC I would be able to transfer that string along as well like so:
This code is in the viewDidLoad
_mainLabel.text = _secondClass.mainLine;
NSLog(@"%@", _secondClass.mainLine);
But that is not working - so cannot I not pass strings in through this way???
Upvotes: 0
Views: 939
Reputation: 55544
The line:
@synthesize mainLine = _mainLine;
means create a getter and setter methods called mainLine
and setMainLine:
respectively, that wrap an instance variable named _mainLine
. (It creates the instance variable for you so the instance variable mainLine
you've declare in the header is not needed)
(The name before the = is the property name, the name after the equals is the name of the ivar it wraps)
You have tried to override the getter but used the name of the instance variable. The getter doesn't start with an underscore so remove the underscore from the method that returns the string.
So in your viewDidLoad
method you are calling the mainLine
method which just returns the _mainLine
instance variable. Your _mainLine
method is never called
If you are just returning a constant string then you don't need the property and ivar at all.
(Also you shouldn't start method names or variables with underscores, as the underscore means by convention it is private and Apple basically reserved all method names starting with an underscore. However it is common to have ivars start with underscores)
Upvotes: 0
Reputation: 104082
Your property is mainLine, so the overridden getter should be -(NSString *)mainLine not -(NSString *)_mainLine.
-(NSString *)mainLine
{
_mainLine = @"This a string from a Class";
return _mainLine;
}
This worked for me. In the ClassVC:
@interface ClassVC : UIViewController
@property (nonatomic, retain) NSString *mainLine;
@end
#import "ClassVC.h"
@implementation ClassVC
-(NSString *)mainLine
{
_mainLine = @"This a string from a Class";
return _mainLine;
}
And this in ViewController:
#import <UIKit/UIKit.h>
@class ClassVC;
@interface ViewController : UIViewController
@property (strong,nonatomic) ClassVC *secondClass;
@property (weak, nonatomic) IBOutlet UILabel *mainLabel;
@end
#import "ViewController.h"
#import "ClassVC.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
ClassVC *secondClass = [[ClassVC alloc] init];
self.mainLabel.text = secondClass.mainLine;
NSLog(@"%@", secondClass.mainLine);
}
Upvotes: 1