Last active
September 23, 2016 20:06
-
-
Save hfossli/3682cd8769bd4d167f6e05ee4b34af8c 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> | |
#define RACNameBlockFromFormat(...) (^NSString *{\ | |
return [NSString stringWithFormat:__VA_ARGS__]; \ | |
}) | |
@interface RACSignal : NSObject | |
- (instancetype)someOperatorWithObject:(NSObject *)object; | |
- (NSString *)name; | |
@end | |
@implementation RACSignal { | |
NSString *(^_nameBlock)(void); | |
} | |
- (instancetype)someOperatorWithObject:(NSObject *)object | |
{ | |
return [self setNameBlock:RACNameBlockFromFormat(@"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