Created
September 26, 2016 12:59
-
-
Save hfossli/840be1207298cc5385fe4028a0d40a88 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 | |
{ | |
@weakify(object); | |
return [self setNameBlock:^NSString *{ | |
@strongify(object); | |
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) int descriptionRequestedCount; | |
@end | |
@implementation Foo | |
- (NSString *)description | |
{ | |
self.descriptionRequestedCount++; | |
return @"<Foo 0xFOOBAR>"; | |
} | |
@end | |
@interface RACSignalTest : XCTestCase | |
@end | |
@implementation RACSignalTest | |
- (void)testFooIsolated | |
{ | |
Foo *foo = [Foo new]; | |
XCTAssertTrue(foo.descriptionRequestedCount == 0, @""); | |
[foo description]; | |
XCTAssertTrue(foo.descriptionRequestedCount == 1, @""); | |
[foo description]; | |
XCTAssertTrue(foo.descriptionRequestedCount == 2, @""); | |
} | |
- (void)testWithSignal | |
{ | |
Foo *foo = [Foo new]; | |
RACSignal *signal = [[RACSignal new] someOperatorWithObject:foo]; | |
XCTAssertTrue(foo.descriptionRequestedCount == 0, @""); | |
XCTAssertEqualObjects([signal name], @"transformed using `someOperatorWithObject` with object <Foo 0xFOOBAR>"); | |
XCTAssertTrue(foo.descriptionRequestedCount == 1, @""); | |
XCTAssertEqualObjects([signal name], @"transformed using `someOperatorWithObject` with object <Foo 0xFOOBAR>"); | |
XCTAssertTrue(foo.descriptionRequestedCount == 1, @""); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment