简体   繁体   中英

Why does this @synthesize implementation return an error in Objective-C?

#import "CLSViewController.h"

@implementation CLSViewController

@synthesize statusText = _statusText;

- (void)viewDidUnload {
    [self setStatusText:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (IBAction)buttonPressed:(UIButton *)sender {
    NSString *title = [sender titleForState:UIControlStateNormal];
->  statusText.text = [NSString stringWithFormat:@"%@ button pressed.", title];
}

@end

The line that says statusText.text = ...

Did I not synthesize it correctly? Removing the = _statusText; from it gets rid of the error, but I thought we were supposed to set it to something.

if you want to access the property, you should use

self.statusText.text = ....

you can also access the variable directly using _statusText:

_statusText.text = ....

If you remove _statusText from the synthesize line, the instance variable name will be assumed to be "statusText", so that is why your situation works when you remove it.

@synthesize statusText
....
statusText.text = [NSString stringWithFormat:@"%@ button pressed.", title]; // this works

IMO you should always access it as a property (eg self.statusText) except in init/dealloc since you are declaring it as such.

the code:

@synthesize statusText = _statusText;

means statusText is a public field of your class, _statusText is a private symbol. Because so you have to modify your code like this:

self.statusText.text = [NSString stringWithFormat:@"%@ button pressed.", title];

or this:

_statusText.text = [NSString stringWithFormat:@"%@ button pressed.", title];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM