Last active
September 13, 2016 19:49
-
-
Save hborders/fe992f760abb021ca9a0b0dc9b1f0417 to your computer and use it in GitHub Desktop.
Why ivars are safer than private properties for private data.
This file contains hidden or 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
// | |
// PlaygroundTests.m | |
// PlaygroundTests | |
// | |
// Created by Borders, Heath on 3/9/16. | |
// Copyright © 2016 Twitch. All rights reserved. | |
// | |
#import <XCTest/XCTest.h> | |
@interface Foo : NSObject | |
- (void)populate:(NSMutableArray<NSString *> * _Nonnull)array; | |
@end | |
@interface Bar : Foo | |
- (void)populate:(NSMutableArray<NSString *> * _Nonnull)array; | |
@end | |
@interface PlaygroundTests : XCTestCase | |
@end | |
@implementation PlaygroundTests | |
- (void)testSameNameIvar | |
{ | |
NSMutableArray<NSString *> * _Nonnull fooArray = [NSMutableArray<NSString *> new]; | |
Foo * _Nonnull foo = [Foo new]; | |
[foo populate:fooArray]; | |
XCTAssertEqualObjects(fooArray, | |
([NSArray<NSString *> arrayWithObjects: | |
@"safeFoo", | |
@"unsafeFoo", | |
nil])); | |
NSMutableArray<NSString *> * _Nonnull barArray = [NSMutableArray<NSString *> new]; | |
Bar * _Nonnull bar = [Bar new]; | |
[bar populate:barArray]; | |
XCTAssertEqualObjects(barArray, | |
([NSArray<NSString *> arrayWithObjects: | |
@"safeFoo", | |
@"unsafeFoo", // this will actually be @"unsafeBar" because Bar.unsafe tramples Foo.unsafe | |
@"safeBar", | |
@"unsafeBar", | |
nil])); | |
} | |
@end | |
@interface Bar () | |
@property (nonatomic) NSString * _Nonnull unsafe; | |
@end | |
@implementation Bar | |
{ | |
NSString * _Nonnull _safe; | |
} | |
- (instancetype _Nonnull)init | |
{ | |
self = [super init]; | |
if (self) | |
{ | |
_safe = @"safeBar"; | |
self.unsafe = @"unsafeBar"; | |
} | |
return self; | |
} | |
#pragma mark - Public API | |
- (void)populate:(NSMutableArray<NSString *> *)array | |
{ | |
[super populate:array]; | |
[array addObject:_safe]; | |
[array addObject:self.unsafe]; | |
} | |
@end | |
@interface Foo () | |
@property (nonatomic) NSString * _Nonnull unsafe; | |
@end | |
@implementation Foo | |
{ | |
NSString * _Nonnull _safe; | |
} | |
- (instancetype _Nonnull)init | |
{ | |
self = [super init]; | |
if (self) | |
{ | |
_safe = @"safeFoo"; | |
self.unsafe = @"unsafeFoo"; | |
} | |
return self; | |
} | |
#pragma mark - Public API | |
- (void)populate:(NSMutableArray<NSString *> *)array | |
{ | |
[array addObject:_safe]; | |
[array addObject:self.unsafe]; | |
} | |
@end |
Author
hborders
commented
Sep 13, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment