RosettaCodeData/Task/Break-OO-privacy/Objective-C/break-oo-privacy-1.m
2023-07-01 13:44:08 -04:00

36 lines
704 B
Objective-C

#import <Foundation/Foundation.h>
@interface Example : NSObject {
@private
NSString *_name;
}
- (instancetype)initWithName:(NSString *)name;
@end
@implementation Example
- (NSString *)description {
return [NSString stringWithFormat:@"Hello, I am %@", _name];
}
- (instancetype)initWithName:(NSString *)name {
if ((self = [super init])) {
_name = [name copy];
}
return self;
}
@end
int main (int argc, const char * argv[]) {
@autoreleasepool{
Example *foo = [[Example alloc] initWithName:@"Eric"];
// get private field
NSLog(@"%@", [foo valueForKey:@"name"]);
// set private field
[foo setValue:@"Edith" forKey:@"name"];
NSLog(@"%@", foo);
}
return 0;
}