0

So I wanted to write a simple class.

header file

#import <Foundation/Foundation.h>

@interface Player : NSObject

@property (readonly, copy) NSString *PlayerName;

@end

class file

#import "Player.h"

@implementation Player

- (NSString*) PlayerName
{
    return _PlayerName;
}

- (void)setPlayerName:(NSString *)PlayerName
{
    _PlayerName = PlayerName;
}

@end

But now Xcode gives me an error, saying that the _PlayerName variable does not exist. But I thought that's the way you need to write properties access functions.

Pascal
  • 2,175
  • 4
  • 39
  • 57

2 Answers2

1

As soon as you override both the setter and getter the compiler no longer creates them for you. Since the compiler is not doing anything with the property it will no longer create the the private ivar.

So unless you need to override the setter or/and getter you better of letting the compiler create them for you.

But if you need just add @synthesize PlayerName = _PlayerName; just after the @implementation.

rckoenes
  • 69,092
  • 8
  • 134
  • 166
0

If you declare the setter AND the getter, you NEED to synthesize the variable, since compiler won't do it automatically for you in this case.

@synthesize PlayerName = _PlayerName;

Also you specified your property as a readonly which is not the best practice to use when you want to save something to that variable, because with dot notation you will get complier error.

sunshinejr
  • 4,834
  • 2
  • 22
  • 32