0
#import "AppDelegate.h"

@interface AppDelegate ()

@property (strong, readwrite, nonatomic) NSNumber *currentNumber;

@end

@implementation AppDelegate


- (NSNumber *)currentNumber {



}

- (void)setCurrentNumber:(NSNumber *)currentNumber {

}
  1. Why I can't access _currentNumber in currentNumber?
  2. If I will remove setCurrentNumber then I can access _currentNumber in currentNumber?
Blazej SLEBODA
  • 8,936
  • 7
  • 53
  • 93

2 Answers2

2

The @property does not cause the ivar generation; rather, it's the implicit @synthesize. However, when you implement both the getter and setter, there is nothing to (implicitly) synthesize, so clang doesn't bother. If you add an explicit @synthesize statement, you'll get your ivar.

Avi
  • 7,469
  • 2
  • 21
  • 22
1

Like Avi mentioned, there is @synthesize keyword. If you just declare property(without implementing getter and setter for it) the corresponding ivar will be generated. Its name will be [underscore][property_name].For example declaring @property currentNumber; leads to implicit applying `@synthesize currentNumber = _currentNumber; But if you want to assign ivar with another name to your property you can declare this ivar and synthesize the property with it:

@interface AppDelegate ()
{
     NSNumber *_anotherIvar;
}
@property (strong, readwrite, nonatomic) NSNumber *currentNumber;

@end

@implementation AppDelegate
@synthesize currentNumber = _anotherIvar;
@end

@synthesize tells the compiler to create corresponding getter and setter which are backed by ivar on the right side of assignment. And if you provide your own setter - you prevent compiler from creating implicit synthesize(and generating ivar), so you need to provide ivar by yourself somehow(for example use explicit synthesize).

Here is good explanation about @synthesize.

Community
  • 1
  • 1
curious
  • 666
  • 4
  • 13