0

I'm trying to make sence of some example code I have. In the .h file a variable is declared in the following fashion

@property (readonly, nonatomic) NSString *username;
@property (readonly, nonatomic, unsafe_unretained) NSURL *avatarImageURL;

in the implementation file

   @private
        NSString *_avatarImageURLString;
    }
   @synthesize username = _username;
- (id)initWithAttributes:(NSDictionary *)attributes {
    self = [super init];
    if (!self) {
        return nil;
    }
    _username = [attributes valueForKeyPath:@"username"];
    _avatarImageURLString = [attributes valueForKeyPath:@"avatar_image.url"];
    return self;
}

- (NSURL *)avatarImageURL {
    return [NSURL URLWithString:_avatarImageURLString];
}

I know that _variable is convention for a variable within a class, but I don't really see why it's done this way. why not just use username directly? why create another variable called. Also, _avatarImageURLString confused me even more, why bother creating a property called avatarImageURL, if you are going to create another called _avatarImageURLString ....

Thanks!

user379468
  • 3,989
  • 10
  • 50
  • 68

2 Answers2

1

It is nothing more than a common convention, but a useful one.

However now, with auto-synthesizing properties it is no longer necessary. Xcode synthesizes a @property xxxx with an ivar named _xxxx behind the scenes.

lakshmen
  • 28,346
  • 66
  • 178
  • 276
0

People did that to make the variables they created different than the xcode ones, and make them simpler and easier to deal with...

But it is no longer as useful as it was, cause now xCode auto-synthesize the variables this way.

Example:

variable when auto-synthesized become _variable

bbarnhart
  • 6,620
  • 1
  • 40
  • 60