Created
September 23, 2016 19:54
-
-
Save hfossli/3f10599e97f7bf544af5aee61e4a4715 to your computer and use it in GitHub Desktop.
Improving setNameWithFormat: in RAC
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 <XCTest/XCTest.h> | |
@interface RACSignal : NSObject | |
- (instancetype)someOperatorWithObject:(NSObject *)object; | |
- (NSString *)name; | |
@end | |
@implementation RACSignal { | |
NSString *(^_nameBlock)(void); | |
} | |
- (instancetype)someOperatorWithObject:(NSObject *)object | |
{ | |
return [self setNameBlock:^NSString *{ | |
return [NSString stringWithFormat:@"transformed using `someOperatorWithObject` with object %@", [object description]]; | |
}]; | |
} | |
- (NSString *)name | |
{ | |
return _nameBlock(); | |
} | |
- (instancetype)setNameBlock:(NSString *(^)(void))nameBlock | |
{ | |
__block NSString *cache; | |
_nameBlock = [^NSString *{ | |
if(cache == nil) | |
{ | |
cache = nameBlock(); | |
} | |
return cache; | |
} copy]; | |
return self; | |
} | |
@end | |
@interface Foo : NSObject | |
@property (nonatomic, assign) BOOL descriptionRequested; | |
@end | |
@implementation Foo | |
- (NSString *)description | |
{ | |
self.descriptionRequested = YES; | |
return @"<Foo 0xFOOBAR>"; | |
} | |
@end | |
@interface RACSignalTest : XCTestCase | |
@end | |
@implementation RACSignalTest | |
- (void)testFooIsolated | |
{ | |
Foo *foo = [Foo new]; | |
XCTAssertTrue(!foo.descriptionRequested, @""); | |
[foo description]; | |
XCTAssertTrue(foo.descriptionRequested, @""); | |
} | |
- (void)testWithSignal | |
{ | |
Foo *foo = [Foo new]; | |
RACSignal *signal = [[RACSignal new] someOperatorWithObject:foo]; | |
XCTAssertTrue(!foo.descriptionRequested, @""); | |
XCTAssertEqualObjects([signal name], @"transformed using `someOperatorWithObject` with object <Foo 0xFOOBAR>"); | |
XCTAssertTrue(foo.descriptionRequested, @""); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment