Last active
August 29, 2015 13:56
-
-
Save k0nserv/8985215 to your computer and use it in GitHub Desktop.
Setter with side effects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface Person | |
@property(nonatomic, copy) NSString *firstName; | |
@property(nonatomic, copy) NSString *lastName; | |
@property(nonatomic, readonly, strong) NSString *fullName | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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