Skip to content

Instantly share code, notes, and snippets.

@k0nserv
Last active August 29, 2015 13:56
Show Gist options
  • Save k0nserv/8985215 to your computer and use it in GitHub Desktop.
Save k0nserv/8985215 to your computer and use it in GitHub Desktop.
Setter with side effects
#import <Foundation/Foundation.h>
@interface Person
@property(nonatomic, copy) NSString *firstName;
@property(nonatomic, copy) NSString *lastName;
@property(nonatomic, readonly, strong) NSString *fullName
@end
#import "person.h"
@interface Person()
// A property can be readonly for the public API, but
// readwrite internally. Again we do not specifiy copy
// because we are in control of creation of the variable
@property(nonatomic, strong) NSString *fullName;
- (void)updateFullName;
@end
@implementation Person
// Optional synthesize, will be auto synthesized
@synthesize fullName = _fullName;
// Because we are overriding the setters we need to
// use explicit synthesize
@synthesize firstName = _firstName, lastName = _lastName;
#pragma mark - Overriden property accessor
- (void)setFirstName:(NSString *)firstName {
if (_firstName != firstName) { // Prevent udpates if the same object is passed again
_firstName = [firstName copy]; // Copy the value to conform with the property
[self updateFullName];
}
}
- (void)setLastName:(NSString *)lastName {
if (_lastName != lastName) {
_lastName = [lastName copy];
[self updateFullName];
}
}
- (void)updateFullName {
// No need for copy here stringWithFormat: creates a new string
self.fullName = [NSString stringWithFormat@"%@ %@", self.firstName, self.lastName];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment