├── HLDeferred ├── Frameworks │ └── .gitignore ├── HLDeferred.xcodeproj │ ├── project.xcworkspace │ │ └── contents.xcworkspacedata │ └── project.pbxproj ├── .gitignore ├── Classes │ ├── HLJSONDataSource.h │ ├── HLFailure.h │ ├── HLDownloadDataSource.h │ ├── HLJSONDataSource.m │ ├── HLDeferredConcurrentDataSource.h │ ├── HLDeferredDataSourceManager.h │ ├── HLFailure.m │ ├── HLDeferredList.h │ ├── HLURLDataSource.h │ ├── HLDeferred.h │ ├── HLDeferredDataSource.h │ ├── HLDownloadDataSource.m │ ├── HLDeferredDataSource.m │ ├── HLDeferredConcurrentDataSource.m │ ├── HLDeferredList.m │ ├── HLDeferredDataSourceManager.m │ ├── HLURLDataSource.m │ ├── JSONKit.h │ ├── HLDeferred.m │ └── JSONKit │ │ └── CHANGELOG.md ├── HLDeferred_Prefix.pch ├── Tests │ ├── HLDeferredTests_Prefix.pch │ ├── HLDeferredTests-Info.plist │ ├── HLDeferredDataSourceTest.m │ ├── HLDeferredConcurrentDataSourceTest.m │ ├── HLURLDataSourceTest.m │ ├── GHUnitIOSTestMain.m │ ├── HLDownloadDataSourceTest.m │ ├── HLJSONDataSourceTest.m │ ├── HLDeferredTest.m │ └── HLDeferredListTest.m └── HLDeferredDataSourceManagerTest.m ├── Documentation └── images │ └── twisted │ ├── deferred.png │ ├── deferred-attach.png │ ├── deferred-process.png │ └── LICENSE.txt ├── LICENSE └── README.md /HLDeferred/Frameworks/.gitignore: -------------------------------------------------------------------------------- 1 | *.framework 2 | -------------------------------------------------------------------------------- /Documentation/images/twisted/deferred.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/heavylifters/HLDeferred-objc/HEAD/Documentation/images/twisted/deferred.png -------------------------------------------------------------------------------- /Documentation/images/twisted/deferred-attach.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/heavylifters/HLDeferred-objc/HEAD/Documentation/images/twisted/deferred-attach.png -------------------------------------------------------------------------------- /Documentation/images/twisted/deferred-process.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/heavylifters/HLDeferred-objc/HEAD/Documentation/images/twisted/deferred-process.png -------------------------------------------------------------------------------- /HLDeferred/HLDeferred.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /HLDeferred/.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | 3 | *.pbxuser 4 | *.perspectivev3 5 | *.mode1v3 6 | *.mode2v3 7 | !default.pbxuser 8 | !default.perspectivev3 9 | !default.mode1v3 10 | !default.mode2v3 11 | 12 | *~.nib 13 | *~.xib 14 | 15 | .DS_Store 16 | 17 | xcuserdata 18 | */xcuserdata 19 | 20 | -------------------------------------------------------------------------------- /HLDeferred/Classes/HLJSONDataSource.h: -------------------------------------------------------------------------------- 1 | // 2 | // HLJSONDataSource.h 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLURLDataSource.h" 10 | 11 | @interface HLJSONDataSource : HLURLDataSource 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /HLDeferred/Classes/HLFailure.h: -------------------------------------------------------------------------------- 1 | // 2 | // HLFailure.h 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | @interface HLFailure : NSObject 10 | { 11 | id value_; 12 | } 13 | 14 | + (HLFailure *) wrap: (id)v; 15 | 16 | - (id) initWithValue: (id)v; 17 | - (id) value; 18 | - (NSError *) valueAsError; 19 | 20 | @end 21 | -------------------------------------------------------------------------------- /HLDeferred/HLDeferred_Prefix.pch: -------------------------------------------------------------------------------- 1 | // 2 | // HLDeferred_Prefix.pch 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | // Prefix header for all source files of the 'CocoaTouchStaticLibrary' target in the 'CocoaTouchStaticLibrary' project. 9 | // 10 | 11 | #ifdef __OBJC__ 12 | #import 13 | #endif 14 | -------------------------------------------------------------------------------- /HLDeferred/Tests/HLDeferredTests_Prefix.pch: -------------------------------------------------------------------------------- 1 | // 2 | // HLDeferredTests_Prefix.pch 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | // Prefix header for all source files of the 'CocoaTouchStaticLibrary' target in the 'CocoaTouchStaticLibrary' project. 9 | // 10 | 11 | #ifdef __OBJC__ 12 | #import 13 | #import 14 | #endif 15 | -------------------------------------------------------------------------------- /HLDeferred/Classes/HLDownloadDataSource.h: -------------------------------------------------------------------------------- 1 | // 2 | // HLDownloadDataSource.h 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLURLDataSource.h" 10 | 11 | @interface HLDownloadDataSource : HLURLDataSource 12 | { 13 | NSFileHandle *fileHandle_; 14 | } 15 | 16 | - (id) initWithSourceURL: (NSURL *)sourceURL destinationPath: (NSString *)destinationPath; 17 | 18 | @end 19 | -------------------------------------------------------------------------------- /HLDeferred/Tests/HLDeferredTests-Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | English 7 | CFBundleExecutable 8 | ${EXECUTABLE_NAME} 9 | CFBundleIdentifier 10 | com.heavylifters.${PRODUCT_NAME:identifier} 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundlePackageType 14 | APPL 15 | CFBundleSignature 16 | ???? 17 | CFBundleVersion 18 | 1.0 19 | 20 | 21 | -------------------------------------------------------------------------------- /HLDeferred/Classes/HLJSONDataSource.m: -------------------------------------------------------------------------------- 1 | // 2 | // HLJSONDataSource.m 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLJSONDataSource.h" 10 | #import "JSONKit.h" 11 | 12 | @implementation HLJSONDataSource 13 | 14 | - (void) responseFinished 15 | { 16 | if ([self responseData]) { 17 | NSError *error = nil; 18 | id result = [[self responseData] objectFromJSONDataWithParseOptions: JKParseOptionStrict error: &error]; 19 | if (result) { 20 | [self setResponseData: nil]; 21 | [self setResult: result]; 22 | [self asyncCompleteOperationResult]; 23 | } else { 24 | [self setError: error]; 25 | [self asyncCompleteOperationError]; 26 | } 27 | } else { 28 | [super responseFinished]; 29 | } 30 | } 31 | 32 | @end 33 | -------------------------------------------------------------------------------- /HLDeferred/Classes/HLDeferredConcurrentDataSource.h: -------------------------------------------------------------------------------- 1 | // 2 | // HLDeferredConcurrentDataSource.h 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLDeferredDataSource.h" 10 | 11 | @interface HLDeferredConcurrentDataSource : HLDeferredDataSource 12 | { 13 | BOOL executing_; 14 | BOOL finished_; 15 | 16 | NSThread *runLoopThread_; 17 | NSSet *runLoopModes_; 18 | } 19 | 20 | @property (retain) NSThread *runLoopThread; // default is nil, implying main thread 21 | @property (copy) NSSet *runLoopModes; // default is nil, implying set containing NSDefaultRunLoopMode 22 | 23 | #pragma mark - 24 | #pragma mark Template methods for subclasses 25 | 26 | // called on the runLoopThread 27 | - (void) execute; 28 | 29 | // if you override this, you MUST call super 30 | // called on the runLoopThread 31 | - (void) cancelOnRunLoopThread; 32 | 33 | @end 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2011 HeavyLifters Network Ltd. All rights reserved. 2 | Permission is hereby granted, free of charge, to any person obtaining a copy 3 | of this software and associated documentation files (the "Software"), to 4 | deal in the Software without restriction, including without limitation the 5 | rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 6 | sell copies of the Software, and to permit persons to whom the Software is 7 | furnished to do so, subject to the following conditions: 8 | 9 | The above copyright notice and this permission notice shall be included in 10 | all copies or substantial portions of the Software. 11 | 12 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 13 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 14 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 15 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 16 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 17 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 18 | IN THE SOFTWARE. 19 | -------------------------------------------------------------------------------- /HLDeferred/Classes/HLDeferredDataSourceManager.h: -------------------------------------------------------------------------------- 1 | // 2 | // HLDeferredDataSourceManager.h 3 | // HLDeferred 4 | // 5 | // Created by Jim Roepcke on 11-07-10. 6 | // Copyright 2011 Jim Roepcke. All rights reserved. 7 | // See included LICENSE file (MIT) for licensing information. 8 | // 9 | 10 | #import "HLDeferred.h" 11 | 12 | @class HLDeferredDataSource; 13 | 14 | @interface HLDeferredDataSourceManager : NSObject 15 | { 16 | BOOL _networkRunLoopThreadContinue; 17 | NSThread *_networkRunLoopThread; 18 | NSOperationQueue *_queueForNetworkTransfers; 19 | NSUInteger _runningNetworkTransferCount; 20 | } 21 | 22 | // observable, always changes on main thread 23 | // you may only access this on the main thread 24 | @property (nonatomic, readonly, assign) BOOL networkInUse; 25 | 26 | // you may only call this on the main thread 27 | - (void) incrementRunningNetworkTransferCount; 28 | // you may only call this on the main thread 29 | - (void) decrementRunningNetworkTransferCount; 30 | 31 | - (id) initWithRunLoopThreadName: (NSString *)name; 32 | 33 | - (HLDeferred *) requestStartNetworkTransferDataSource: (HLDeferredDataSource *)ds; 34 | 35 | - (void) stop: (HLVoidBlock)completion; 36 | 37 | @end 38 | -------------------------------------------------------------------------------- /HLDeferred/Classes/HLFailure.m: -------------------------------------------------------------------------------- 1 | // 2 | // HLFailure.m 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLFailure.h" 10 | 11 | @implementation HLFailure 12 | 13 | - (id) initWithValue: (id)v 14 | { 15 | self = [super init]; 16 | if (self) { 17 | value_ = [([v isKindOfClass: [HLFailure class]] ? [(HLFailure *)v value] : v) retain]; 18 | } 19 | return self; 20 | } 21 | 22 | - (id) init 23 | { 24 | self = [self initWithValue: nil]; 25 | return self; 26 | } 27 | 28 | - (void) dealloc 29 | { 30 | [value_ release]; value_ = nil; 31 | [super dealloc]; 32 | } 33 | 34 | + (HLFailure *) wrap: (id)v 35 | { 36 | if ([v isKindOfClass: [HLFailure class]]) return v; 37 | return [[[[self class] alloc] initWithValue: v] autorelease]; 38 | } 39 | 40 | - (id) value { return value_; } 41 | 42 | - (NSError *) valueAsError 43 | { 44 | if ([value_ isKindOfClass: [NSError class]]) { 45 | return value_; 46 | } else { 47 | return [NSError errorWithDomain: @"HLFailure" code: 0 userInfo: [NSDictionary dictionaryWithObject: value_ forKey: @"value"]]; 48 | } 49 | } 50 | 51 | @end 52 | -------------------------------------------------------------------------------- /HLDeferred/Classes/HLDeferredList.h: -------------------------------------------------------------------------------- 1 | // 2 | // HLDeferredList.h 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLDeferred.h" 10 | 11 | @interface HLDeferredList : HLDeferred 12 | { 13 | NSArray *deferreds_; 14 | NSMutableArray *results_; 15 | BOOL fireOnFirstResult_; 16 | BOOL fireOnFirstError_; 17 | BOOL consumeErrors_; 18 | NSUInteger finishedCount_; 19 | BOOL cancelDeferredsWhenCancelled_; 20 | } 21 | 22 | - (id) initWithDeferreds: (NSArray *)list 23 | fireOnFirstResult: (BOOL)flFireOnFirstResult 24 | fireOnFirstError: (BOOL)flFireOnFirstError 25 | consumeErrors: (BOOL)flConsumeErrors; 26 | 27 | - (id) initWithDeferreds: (NSArray *)list; 28 | - (id) initWithDeferreds: (NSArray *)list fireOnFirstResult: (BOOL)flFireOnFirstResult; 29 | - (id) initWithDeferreds: (NSArray *)list fireOnFirstResult: (BOOL)flFireOnFirstResult consumeErrors: (BOOL)flConsumeErrors; 30 | - (id) initWithDeferreds: (NSArray *)list fireOnFirstError: (BOOL)flFireOnFirstError; 31 | - (id) initWithDeferreds: (NSArray *)list consumeErrors: (BOOL)flConsumeErrors; 32 | 33 | - (void) cancelDeferredsWhenCancelled; 34 | 35 | @end 36 | -------------------------------------------------------------------------------- /HLDeferred/Classes/HLURLDataSource.h: -------------------------------------------------------------------------------- 1 | // 2 | // HLURLDataSource.h 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLDeferredConcurrentDataSource.h" 10 | 11 | @interface HLURLDataSource : HLDeferredConcurrentDataSource 12 | { 13 | NSURLConnection *conn_; 14 | NSURLResponse *response_; 15 | NSMutableData *responseData_; 16 | NSDictionary *context_; 17 | } 18 | 19 | @property (nonatomic, retain) NSDictionary *context; 20 | @property (nonatomic, retain) NSMutableData *responseData; 21 | 22 | // designated initializer 23 | - (id) initWithContext: (NSDictionary *)aContext; 24 | 25 | // convenience initializers 26 | - (id) initWithURL: (NSURL *)url; 27 | - (id) initWithURLString: (NSString *)urlString; 28 | 29 | + (HLURLDataSource *) postToURL: (NSURL *)url 30 | withBody: (NSString *)body; 31 | 32 | - (NSString *) responseHeaderValueForKey: (NSString *)key; 33 | - (NSInteger) responseStatusCode; 34 | 35 | - (BOOL) entityWasOK; 36 | - (BOOL) entityWasNotModified; 37 | - (BOOL) entityWasNotFound; 38 | 39 | #pragma mark - 40 | #pragma mark Public API: template methods, override these to customize behaviour (do NOT call directly) 41 | 42 | - (NSMutableURLRequest *) urlRequest; 43 | 44 | - (BOOL) responseBegan; 45 | - (void) responseReceivedData: (NSData *)data; 46 | - (void) responseFinished; 47 | - (void) responseFailed; 48 | 49 | @end 50 | -------------------------------------------------------------------------------- /Documentation/images/twisted/LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2001-2010 2 | Allen Short 3 | Andy Gayton 4 | Andrew Bennetts 5 | Antoine Pitrou 6 | Apple Computer, Inc. 7 | Benjamin Bruheim 8 | Bob Ippolito 9 | Canonical Limited 10 | Christopher Armstrong 11 | David Reid 12 | Donovan Preston 13 | Eric Mangold 14 | Eyal Lotem 15 | Itamar Shtull-Trauring 16 | James Knight 17 | Jason A. Mobarak 18 | Jean-Paul Calderone 19 | Jessica McKellar 20 | Jonathan Jacobs 21 | Jonathan Lange 22 | Jonathan D. Simms 23 | Jürgen Hermann 24 | Kevin Horn 25 | Kevin Turner 26 | Mary Gardiner 27 | Matthew Lefkowitz 28 | Massachusetts Institute of Technology 29 | Moshe Zadka 30 | Paul Swartz 31 | Pavel Pergamenshchik 32 | Ralph Meijer 33 | Sean Riley 34 | Software Freedom Conservancy 35 | Travis B. Hartwell 36 | Thijs Triemstra 37 | Thomas Herve 38 | Timothy Allen 39 | 40 | Permission is hereby granted, free of charge, to any person obtaining 41 | a copy of this software and associated documentation files (the 42 | "Software"), to deal in the Software without restriction, including 43 | without limitation the rights to use, copy, modify, merge, publish, 44 | distribute, sublicense, and/or sell copies of the Software, and to 45 | permit persons to whom the Software is furnished to do so, subject to 46 | the following conditions: 47 | 48 | The above copyright notice and this permission notice shall be 49 | included in all copies or substantial portions of the Software. 50 | 51 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 52 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 53 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 54 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 55 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 56 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 57 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 58 | -------------------------------------------------------------------------------- /HLDeferred/Tests/HLDeferredDataSourceTest.m: -------------------------------------------------------------------------------- 1 | // 2 | // HLDeferredDataSourceTest.m 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLDeferredDataSource.h" 10 | 11 | @interface HLDeferredDataSourceTestDataSource : HLDeferredDataSource 12 | { 13 | BOOL success; 14 | } 15 | 16 | - (BOOL) succeeded; 17 | 18 | @end 19 | 20 | @interface HLDeferredDataSourceTest : GHAsyncTestCase 21 | @end 22 | 23 | @implementation HLDeferredDataSourceTest 24 | 25 | - (void) testStart 26 | { 27 | [self prepare]; 28 | 29 | HLDeferredDataSourceTestDataSource *ds = [[HLDeferredDataSourceTestDataSource alloc] init]; 30 | HLDeferred *d = [ds requestStartOnQueue: [NSOperationQueue mainQueue]]; 31 | 32 | __block BOOL success = NO; 33 | __block NSException *blockException = nil; 34 | 35 | [d then: ^(id result) { 36 | @try { 37 | success = YES; 38 | GHAssertEqualStrings(@"ok", result, @"unexpected result"); 39 | [self notify: kGHUnitWaitStatusSuccess forSelector: @selector(testStart)]; 40 | } @catch (NSException *exception) { 41 | blockException = [exception retain]; 42 | } @finally { 43 | return result; 44 | } 45 | }]; 46 | 47 | [self waitForStatus: kGHUnitWaitStatusSuccess timeout: 5.0]; 48 | GHAssertTrue([ds succeeded], @"data source wasn't executed"); 49 | GHAssertTrue(success, @"callback didn't run"); 50 | GHAssertNil([blockException autorelease], @"%@", blockException); 51 | [ds release]; ds = nil; 52 | } 53 | 54 | @end 55 | 56 | @implementation HLDeferredDataSourceTestDataSource 57 | 58 | - (id) init 59 | { 60 | self = [super init]; 61 | return self; 62 | } 63 | 64 | - (void) execute 65 | { 66 | success = YES; 67 | [self setResult: @"ok"]; 68 | [self asyncCompleteOperationResult]; 69 | } 70 | 71 | - (BOOL) succeeded 72 | { 73 | return success; 74 | } 75 | 76 | @end 77 | -------------------------------------------------------------------------------- /HLDeferred/Tests/HLDeferredConcurrentDataSourceTest.m: -------------------------------------------------------------------------------- 1 | // 2 | // HLDeferredConcurrentDataSourceTest.m 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLDeferredConcurrentDataSource.h" 10 | 11 | @interface HLDeferredConcurrentDataSourceTestDataSource : HLDeferredConcurrentDataSource 12 | { 13 | BOOL success; 14 | } 15 | 16 | - (BOOL) succeeded; 17 | 18 | @end 19 | 20 | @interface HLDeferredConcurrentDataSourceTest : GHAsyncTestCase 21 | @end 22 | 23 | @implementation HLDeferredConcurrentDataSourceTest 24 | 25 | - (void) testStart 26 | { 27 | [self prepare]; 28 | 29 | HLDeferredConcurrentDataSourceTestDataSource *ds = [[HLDeferredConcurrentDataSourceTestDataSource alloc] init]; 30 | HLDeferred *d = [ds requestStartOnQueue: [NSOperationQueue mainQueue]]; 31 | 32 | __block BOOL success = NO; 33 | __block NSException *blockException = nil; 34 | 35 | [d then: ^(id result) { 36 | @try { 37 | success = YES; 38 | GHAssertEqualStrings(@"ok", result, @"unexpected result"); 39 | [self notify: kGHUnitWaitStatusSuccess forSelector: @selector(testStart)]; 40 | } @catch (NSException *exception) { 41 | blockException = [exception retain]; 42 | } @finally { 43 | return result; 44 | } 45 | }]; 46 | 47 | [self waitForStatus: kGHUnitWaitStatusSuccess timeout: 5.0]; 48 | GHAssertTrue([ds succeeded], @"concurrent data source wasn't executed"); 49 | GHAssertTrue(success, @"callback didn't run"); 50 | GHAssertNil([blockException autorelease], @"%@", blockException); 51 | [ds release]; ds = nil; 52 | } 53 | 54 | @end 55 | 56 | @implementation HLDeferredConcurrentDataSourceTestDataSource 57 | 58 | - (id) init 59 | { 60 | self = [super init]; 61 | return self; 62 | } 63 | 64 | - (void) execute 65 | { 66 | success = YES; 67 | dispatch_async(dispatch_get_main_queue(), ^{ 68 | [self setResult: @"ok"]; 69 | [self asyncCompleteOperationResult]; 70 | }); 71 | } 72 | 73 | - (BOOL) succeeded 74 | { 75 | return success; 76 | } 77 | 78 | @end 79 | -------------------------------------------------------------------------------- /HLDeferred/Classes/HLDeferred.h: -------------------------------------------------------------------------------- 1 | // 2 | // HLDeferred.h 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLFailure.h" 10 | 11 | extern NSString * const kHLDeferredCancelled; 12 | extern NSString * const kHLDeferredNoResult; 13 | extern NSString * const HLDeferredAlreadyCalledException; 14 | extern NSString * const HLDeferredAlreadyFinalizedException; 15 | 16 | typedef id (^ThenBlock)(id result); 17 | typedef id (^FailBlock)(HLFailure *failure); 18 | typedef void (^HLVoidBlock)(void); 19 | 20 | @class HLDeferred; 21 | @class HLLink; 22 | 23 | @protocol HLDeferredCancellable 24 | 25 | - (void) deferredWillCancel: (HLDeferred *)d; 26 | 27 | @end 28 | 29 | @interface HLDeferred : NSObject 30 | { 31 | BOOL finalized_; 32 | BOOL called_; 33 | BOOL suppressAlreadyCalled_; 34 | BOOL runningCallbacks_; 35 | id result_; 36 | NSInteger pauseCount_; 37 | NSMutableArray *chain_; 38 | id canceller_; 39 | HLLink *finalizer_; 40 | 41 | HLDeferred *chainedTo_; 42 | } 43 | 44 | @property (nonatomic, assign) id canceller; 45 | @property (nonatomic, readonly, assign, getter=isCalled) BOOL called; 46 | 47 | // designated initializer 48 | - (id) initWithCanceller: (id ) theCanceller; 49 | - (id) init; // calls initWithCanceller: nil 50 | 51 | + (HLDeferred *) deferredWithResult: (id)result; 52 | + (HLDeferred *) deferredWithError: (id)error; 53 | + (HLDeferred *) deferredObserving: (HLDeferred *)otherDeferred; 54 | 55 | - (HLDeferred *) then: (ThenBlock)cb; 56 | - (HLDeferred *) fail: (FailBlock)eb; 57 | - (HLDeferred *) both: (ThenBlock)bb; 58 | 59 | - (HLDeferred *) then: (ThenBlock)cb fail: (FailBlock)eb; 60 | 61 | - (HLDeferred *) thenReturn: (id)aResult; 62 | 63 | - (HLDeferred *) thenFinally: (ThenBlock)aThenFinalizer; 64 | - (HLDeferred *) failFinally: (FailBlock)aFailFinalizer; 65 | - (HLDeferred *) bothFinally: (ThenBlock)aBothFinalizer; 66 | 67 | - (HLDeferred *) thenFinally: (ThenBlock)atThenFinalizer failFinally: (FailBlock)aFailFinalizer; 68 | 69 | - (HLDeferred *) takeResult: (id)aResult; 70 | - (HLDeferred *) takeError: (id)anError; 71 | - (HLDeferred *) notify: (HLDeferred *)otherDeferred; 72 | - (void) cancel; 73 | 74 | @end 75 | -------------------------------------------------------------------------------- /HLDeferred/HLDeferredDataSourceManagerTest.m: -------------------------------------------------------------------------------- 1 | // 2 | // HLDeferredDataSourceManagerTest.m 3 | // HLDeferred 4 | // 5 | // Created by Jim Roepcke on 11-07-19. 6 | // Copyright 2011 Jim Roepcke. All rights reserved. 7 | // See included LICENSE file (MIT) for licensing information. 8 | // 9 | 10 | #import "HLURLDataSource.h" 11 | #import "HLDeferredDataSourceManager.h" 12 | 13 | @interface HLDeferredDataSourceManagerTest : GHAsyncTestCase 14 | @end 15 | 16 | @implementation HLDeferredDataSourceManagerTest 17 | 18 | - (void) testRequestStartNetworkTransferDataSource 19 | { 20 | [self prepare]; 21 | 22 | HLDeferredDataSourceManager *mgr = [[HLDeferredDataSourceManager alloc] 23 | initWithRunLoopThreadName: 24 | @"testRequestStartNetworkTransferDataSource"]; 25 | GHAssertNotNil(mgr, nil); 26 | 27 | HLURLDataSource *ds = [[HLURLDataSource alloc] initWithURLString: @"http://www.google.com/"]; 28 | [ds setCallingThread: [NSThread mainThread]]; 29 | GHAssertNotNil(ds, nil); 30 | 31 | HLDeferred *d = [mgr requestStartNetworkTransferDataSource: ds]; 32 | GHAssertNotNil(d, nil); 33 | 34 | __block BOOL success = NO; 35 | __block id theResult = nil; 36 | __block NSThread *theThread = nil; 37 | [d then: ^(id result) { 38 | success = YES; 39 | theThread = [[NSThread currentThread] retain]; 40 | theResult = [result retain]; 41 | [self notify: kGHUnitWaitStatusSuccess forSelector: @selector(testRequestStartNetworkTransferDataSource)]; 42 | return result; 43 | }]; 44 | 45 | [self waitForStatus: kGHUnitWaitStatusSuccess timeout: 10.0]; 46 | GHAssertTrue(success, @"callback didn't run"); 47 | GHAssertEquals(theThread, [NSThread mainThread], nil); 48 | GHAssertNotNil(theResult, nil); 49 | [theResult release]; theResult = nil; 50 | [theThread release]; theThread = nil; 51 | d = nil; 52 | 53 | [self prepare]; 54 | [mgr stop: ^{ 55 | [self notify: kGHUnitWaitStatusSuccess 56 | forSelector: @selector(testRequestStartNetworkTransferDataSource)]; 57 | }]; 58 | [self waitForStatus: kGHUnitWaitStatusSuccess timeout: 10.0]; 59 | [ds release]; ds = nil; 60 | [mgr release]; mgr = nil; 61 | } 62 | 63 | - (void) testStop 64 | { 65 | [self prepare]; 66 | 67 | HLDeferredDataSourceManager *mgr = [[HLDeferredDataSourceManager alloc] 68 | initWithRunLoopThreadName: 69 | @"testStop"]; 70 | GHAssertNotNil(mgr, nil); 71 | 72 | [mgr stop: ^{ 73 | [self notify: kGHUnitWaitStatusSuccess 74 | forSelector: @selector(testStop)]; 75 | }]; 76 | [self waitForStatus: kGHUnitWaitStatusSuccess timeout: 10.0]; 77 | [mgr release]; mgr = nil; 78 | } 79 | 80 | @end 81 | -------------------------------------------------------------------------------- /HLDeferred/Classes/HLDeferredDataSource.h: -------------------------------------------------------------------------------- 1 | // 2 | // HLDeferredDataSource.h 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLDeferred.h" 10 | 11 | // Subclassing note: 12 | 13 | // DO NOT OVERRIDE -start OR -main unless you're SURE it's okay. 14 | // HLDeferredDataSource and HLDeferredConcurrentDataSource are 15 | // designed to do the right thing if you override -execute. 16 | 17 | @interface HLDeferredDataSource : NSOperation 18 | { 19 | id error_; 20 | id result_; 21 | HLDeferred *deferred_; 22 | NSThread *callingThread_; 23 | } 24 | 25 | // the deferred will receive its result on this thread 26 | // the thread must be running its run loop 27 | // it will be set to [NSThread currentThread] when 28 | // -requestStartOnQueue: is called, iff it is nil. 29 | @property (retain) NSThread *callingThread; 30 | 31 | @property (retain) id result; 32 | @property (retain) id error; 33 | 34 | - (NSThread *) actualCallingThread; 35 | - (BOOL) isActualCallingThread; 36 | 37 | #pragma mark - 38 | #pragma mark HLDeferred support 39 | 40 | // This NSOperation will be added to and retained by the queue, so it is 41 | // safe to release this operation after calling this method. 42 | // Note: the returned HLDeferred is retained by this operation, so you 43 | // are not required to retain the returned HLDeferred to ensure it and its 44 | // callbacks survive until the operation is complete. 45 | // 46 | // Note that this method returns an HLDeferred and the name of the method 47 | // starts with "request". This is a coding convention we suggest you follow: 48 | // "The name of methods returning (HLDeferred *) should start with request" 49 | - (HLDeferred *) requestStartOnQueue: (NSOperationQueue *)queue; 50 | 51 | // sends -takeResult: to the HLDeferred, on the main thread using dispatch_async 52 | // the result is from [self result], so call -setResult: before you call this 53 | - (void) asyncCompleteOperationResult; 54 | 55 | // sends -takeError: to the HLDeferred, on the main thread using dispatch_async 56 | // the error is from [self error], so call -setError: before you call this 57 | - (void) asyncCompleteOperationError; 58 | 59 | #pragma mark - 60 | #pragma mark Template methods for subclasses 61 | 62 | // Override this and do what you need to do. 63 | // The default implementation does nothing. 64 | // Your execute method should: 65 | // - call -setResult: then -asyncCompleteOperationResult 66 | // or 67 | // - call -setError: then -asyncCompleteOperationError 68 | // DO NOT CALL THIS YOURSELF 69 | - (void) execute; 70 | 71 | // Optionally override this 72 | // Called after the HLDeferred's callback chain has run. 73 | // DO NOT CALL THIS YOURSELF except to call super, which 74 | // you MUST do if you override this 75 | - (void) markOperationCompleted; 76 | 77 | @end 78 | -------------------------------------------------------------------------------- /HLDeferred/Tests/HLURLDataSourceTest.m: -------------------------------------------------------------------------------- 1 | // 2 | // HLURLDataSource.m 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLURLDataSource.h" 10 | 11 | @interface HLURLDataSourceTest : GHAsyncTestCase 12 | @end 13 | 14 | @implementation HLURLDataSourceTest : GHAsyncTestCase 15 | 16 | - (void) testSimple 17 | { 18 | [self prepare]; 19 | 20 | HLURLDataSource *ds = [[HLURLDataSource alloc] initWithURLString: @"http://www.google.com/"]; 21 | HLDeferred *d = [ds requestStartOnQueue: [NSOperationQueue mainQueue]]; 22 | [ds release]; ds = nil; 23 | 24 | __block BOOL success = NO; 25 | __block id theResult = nil; 26 | 27 | [d then: ^(id result) { 28 | success = YES; 29 | theResult = [result retain]; 30 | [self notify: kGHUnitWaitStatusSuccess forSelector: @selector(testSimple)]; 31 | return result; 32 | } fail: ^(HLFailure *failure) { 33 | [self notify: kGHUnitWaitStatusFailure forSelector: @selector(testSimple)]; 34 | return failure; 35 | }]; 36 | [self waitForStatus: kGHUnitWaitStatusSuccess timeout: 5.0]; 37 | GHAssertTrue(success, @"callback didn't run"); 38 | GHAssertTrue([theResult isKindOfClass: [NSData class]], @"expected NSData"); 39 | [theResult release]; theResult = nil; 40 | } 41 | 42 | - (void) testFail 43 | { 44 | [self prepare]; 45 | 46 | HLURLDataSource *ds = [[HLURLDataSource alloc] initWithURLString: @"random-!-string://foo/bar"]; 47 | HLDeferred *d = [ds requestStartOnQueue: [NSOperationQueue mainQueue]]; 48 | [ds release]; ds = nil; 49 | 50 | __block BOOL success = NO; 51 | 52 | [d then: ^(id result) { 53 | [self notify: kGHUnitWaitStatusFailure forSelector: @selector(testFail)]; 54 | return result; 55 | } fail: ^(HLFailure *failure) { 56 | success = YES; 57 | [self notify: kGHUnitWaitStatusSuccess forSelector: @selector(testFail)]; 58 | return failure; 59 | }]; 60 | [self waitForStatus: kGHUnitWaitStatusSuccess timeout: 5.0]; 61 | GHAssertTrue(success, @"errback didn't run"); 62 | } 63 | 64 | - (void) testNotFound 65 | { 66 | [self prepare]; 67 | 68 | HLURLDataSource *ds = [[HLURLDataSource alloc] initWithURLString: @"http://google.com/asdfasdfasdf"]; 69 | HLDeferred *d = [ds requestStartOnQueue: [NSOperationQueue mainQueue]]; 70 | 71 | __block BOOL success = NO; 72 | __block id theResult = nil; 73 | 74 | [d then: ^(id result) { 75 | success = YES; 76 | theResult = [result retain]; 77 | [self notify: kGHUnitWaitStatusSuccess forSelector: @selector(testNotFound)]; 78 | return result; 79 | } fail: ^(HLFailure *failure) { 80 | [self notify: kGHUnitWaitStatusFailure forSelector: @selector(testNotFound)]; 81 | return failure; 82 | }]; 83 | [self waitForStatus: kGHUnitWaitStatusSuccess timeout: 5.0]; 84 | GHAssertTrue(success, @"callback didn't run"); 85 | GHAssertNil(theResult, nil); 86 | [theResult release]; theResult = nil; 87 | [ds release]; ds = nil; 88 | } 89 | 90 | @end 91 | -------------------------------------------------------------------------------- /HLDeferred/Tests/GHUnitIOSTestMain.m: -------------------------------------------------------------------------------- 1 | // 2 | // GHUnitIOSTestMain.m 3 | // GHUnitIPhone 4 | // 5 | // Created by Gabriel Handford on 1/25/09. 6 | // Copyright 2009. All rights reserved. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the "Software"), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | // copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #import 31 | 32 | // If you are using the framework 33 | #import 34 | // If you are using the static library and importing header files manually 35 | //#import "GHUnit.h" 36 | 37 | // Default exception handler 38 | void exceptionHandler(NSException *exception) { 39 | NSLog(@"%@\n%@", [exception reason], GHUStackTraceFromException(exception)); 40 | } 41 | 42 | int main(int argc, char *argv[]) { 43 | 44 | /*! 45 | For debugging: 46 | Go into the "Get Info" contextual menu of your (test) executable (inside the "Executables" group in the left panel of XCode). 47 | Then go in the "Arguments" tab. You can add the following environment variables: 48 | 49 | Default: Set to: 50 | NSDebugEnabled NO "YES" 51 | NSZombieEnabled NO "YES" 52 | NSDeallocateZombies NO "YES" 53 | NSHangOnUncaughtException NO "YES" 54 | 55 | NSEnableAutoreleasePool YES "NO" 56 | NSAutoreleaseFreedObjectCheckEnabled NO "YES" 57 | NSAutoreleaseHighWaterMark 0 non-negative integer 58 | NSAutoreleaseHighWaterResolution 0 non-negative integer 59 | 60 | For info on these varaiables see NSDebug.h; http://theshadow.uw.hu/iPhoneSDKdoc/Foundation.framework/NSDebug.h.html 61 | 62 | For malloc debugging see: http://developer.apple.com/mac/library/documentation/Performance/Conceptual/ManagingMemory/Articles/MallocDebug.html 63 | */ 64 | 65 | NSSetUncaughtExceptionHandler(&exceptionHandler); 66 | 67 | NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 68 | 69 | // Register any special test case classes 70 | //[[GHTesting sharedInstance] registerClassName:@"GHSpecialTestCase"]; 71 | 72 | int retVal = 0; 73 | // If GHUNIT_CLI is set we are using the command line interface and run the tests 74 | // Otherwise load the GUI app 75 | if (getenv("GHUNIT_CLI")) { 76 | retVal = [GHTestRunner run]; 77 | } else { 78 | retVal = UIApplicationMain(argc, argv, nil, @"GHUnitIPhoneAppDelegate"); 79 | } 80 | [pool release]; 81 | return retVal; 82 | } 83 | -------------------------------------------------------------------------------- /HLDeferred/Classes/HLDownloadDataSource.m: -------------------------------------------------------------------------------- 1 | // 2 | // HLDownloadDataSource.m 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLDownloadDataSource.h" 10 | 11 | 12 | @implementation HLDownloadDataSource 13 | 14 | - (id) initWithSourceURL: (NSURL *)sourceURL destinationPath: (NSString *)destinationPath 15 | { 16 | self = [super initWithContext: [NSDictionary dictionaryWithObjectsAndKeys: 17 | sourceURL, @"sourceURL", 18 | destinationPath, @"destinationPath", 19 | nil]]; 20 | if (self) { 21 | fileHandle_ = nil; 22 | } 23 | return self; 24 | } 25 | 26 | - (void) dealloc 27 | { 28 | [fileHandle_ release]; fileHandle_ = nil; 29 | [super dealloc]; 30 | } 31 | 32 | #pragma mark - 33 | #pragma mark Private API 34 | 35 | - (NSURL *) sourceURL 36 | { 37 | return [[self context] objectForKey: @"sourceURL"]; 38 | } 39 | 40 | - (NSString *) destinationPath 41 | { 42 | return [[self context] objectForKey: @"destinationPath"]; 43 | } 44 | 45 | #pragma mark - 46 | #pragma mark Public API: template methods 47 | 48 | - (NSMutableURLRequest *) urlRequest 49 | { 50 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [self sourceURL] 51 | cachePolicy: NSURLRequestReloadIgnoringLocalCacheData 52 | timeoutInterval: 240.0]; 53 | [request setHTTPMethod: @"GET"]; 54 | [request setValue: @"gzip" forHTTPHeaderField: @"Accept-Encoding"]; 55 | NSString *lastModified = [[self context] objectForKey: @"requestIfModifiedSince"]; 56 | if (lastModified) [request setValue: lastModified forHTTPHeaderField: @"If-Modified-Since"]; 57 | return request; 58 | } 59 | 60 | - (void) execute 61 | { 62 | if ([[NSFileManager defaultManager] fileExistsAtPath: [self destinationPath]]) { 63 | [self setResult: [self destinationPath]]; 64 | [self asyncCompleteOperationResult]; 65 | } else { 66 | [super execute]; 67 | } 68 | } 69 | 70 | - (BOOL) responseBegan 71 | { 72 | if ([super responseBegan]) { 73 | [self setResponseData: nil]; 74 | if ([[NSFileManager defaultManager] createFileAtPath: [self destinationPath] 75 | contents: [NSData data] 76 | attributes: nil]) { 77 | [fileHandle_ release]; 78 | fileHandle_ = [[NSFileHandle fileHandleForWritingAtPath: [self destinationPath]] retain]; 79 | return YES; 80 | } 81 | } 82 | return NO; 83 | } 84 | 85 | - (void) responseReceivedData: (NSData *)data 86 | { 87 | if (fileHandle_) { 88 | [fileHandle_ writeData: data]; 89 | } 90 | } 91 | 92 | - (void) responseFinished 93 | { 94 | if (fileHandle_) { 95 | [fileHandle_ release]; fileHandle_ = nil; 96 | [self setResult: [self destinationPath]]; 97 | } 98 | [super responseFinished]; 99 | } 100 | 101 | #pragma mark - 102 | #pragma mark NSOperation support 103 | 104 | - (void) cancelOnRunLoopThread 105 | { 106 | if (fileHandle_) { 107 | [fileHandle_ release]; fileHandle_ = nil; 108 | [[NSFileManager defaultManager] removeItemAtPath: [self destinationPath] 109 | error: NULL]; 110 | } 111 | [super cancelOnRunLoopThread]; 112 | } 113 | 114 | @end 115 | -------------------------------------------------------------------------------- /HLDeferred/Tests/HLDownloadDataSourceTest.m: -------------------------------------------------------------------------------- 1 | // 2 | // HLDownloadDataSourceTest.m 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLDownloadDataSource.h" 10 | 11 | @interface HLDownloadDataSourceTest : GHAsyncTestCase 12 | @end 13 | 14 | static NSString *path; 15 | 16 | @implementation HLDownloadDataSourceTest 17 | 18 | - (void) setUpClass 19 | { 20 | path = [[NSTemporaryDirectory() stringByAppendingPathComponent: @"test"] retain]; 21 | } 22 | 23 | - (void) tearDownClass 24 | { 25 | [path release]; path = nil; 26 | } 27 | 28 | - (void) setUp 29 | { 30 | [[NSFileManager defaultManager] removeItemAtPath: path error: NULL]; 31 | } 32 | 33 | - (void) testSimple 34 | { 35 | [self prepare]; 36 | 37 | HLDownloadDataSource *ds = [[HLDownloadDataSource alloc] initWithSourceURL: [NSURL URLWithString: @"http://www.google.com/"] 38 | destinationPath: path]; 39 | HLDeferred *d = [ds requestStartOnQueue: [NSOperationQueue mainQueue]]; 40 | [ds release]; ds = nil; 41 | 42 | __block BOOL success = NO; 43 | __block id theResult = nil; 44 | 45 | [d then: ^(id result) { 46 | success = YES; 47 | theResult = [result retain]; 48 | [self notify: kGHUnitWaitStatusSuccess forSelector: @selector(testSimple)]; 49 | return result; 50 | } fail: ^(HLFailure *failure) { 51 | [self notify: kGHUnitWaitStatusFailure forSelector: @selector(testSimple)]; 52 | return failure; 53 | }]; 54 | [self waitForStatus: kGHUnitWaitStatusSuccess timeout: 5.0]; 55 | GHAssertTrue(success, @"callback didn't run"); 56 | GHAssertTrue([theResult isKindOfClass: [NSString class]], @"expected NSData"); 57 | GHAssertEqualStrings(theResult, path, nil); 58 | [theResult release]; theResult = nil; 59 | } 60 | 61 | - (void) testFail 62 | { 63 | [self prepare]; 64 | 65 | HLDownloadDataSource *ds = [[HLDownloadDataSource alloc] initWithSourceURL: [NSURL URLWithString: @"random-!-string://foo/bar"] 66 | destinationPath: path]; 67 | HLDeferred *d = [ds requestStartOnQueue: [NSOperationQueue mainQueue]]; 68 | [ds release]; ds = nil; 69 | 70 | __block BOOL success = NO; 71 | 72 | [d then: ^(id result) { 73 | [self notify: kGHUnitWaitStatusFailure forSelector: @selector(testFail)]; 74 | return result; 75 | } fail: ^(HLFailure *failure) { 76 | success = YES; 77 | [self notify: kGHUnitWaitStatusSuccess forSelector: @selector(testFail)]; 78 | return failure; 79 | }]; 80 | [self waitForStatus: kGHUnitWaitStatusSuccess timeout: 5.0]; 81 | GHAssertTrue(success, @"errback didn't run"); 82 | } 83 | 84 | - (void) testNotFound 85 | { 86 | [self prepare]; 87 | 88 | HLDownloadDataSource *ds = [[HLDownloadDataSource alloc] initWithSourceURL: [NSURL URLWithString: @"http://google.com/asdfasdfasdf"] 89 | destinationPath: path]; 90 | HLDeferred *d = [ds requestStartOnQueue: [NSOperationQueue mainQueue]]; 91 | [ds release]; ds = nil; 92 | 93 | __block BOOL success = NO; 94 | __block id theResult = nil; 95 | 96 | [d then: ^(id result) { 97 | success = YES; 98 | theResult = [result retain]; 99 | [self notify: kGHUnitWaitStatusSuccess forSelector: @selector(testNotFound)]; 100 | return result; 101 | } fail: ^(HLFailure *failure) { 102 | [self notify: kGHUnitWaitStatusFailure forSelector: @selector(testNotFound)]; 103 | return failure; 104 | }]; 105 | [self waitForStatus: kGHUnitWaitStatusSuccess timeout: 5.0]; 106 | GHAssertTrue(success, @"callback didn't run"); 107 | GHAssertNil(theResult, nil); 108 | [theResult release]; theResult = nil; 109 | 110 | } 111 | 112 | @end 113 | -------------------------------------------------------------------------------- /HLDeferred/Classes/HLDeferredDataSource.m: -------------------------------------------------------------------------------- 1 | // 2 | // HLDeferredDataSource.m 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLDeferredDataSource.h" 10 | 11 | @implementation HLDeferredDataSource 12 | 13 | @synthesize callingThread=callingThread_; 14 | @synthesize result=result_; 15 | @synthesize error=error_; 16 | 17 | - (id) init 18 | { 19 | self = [super init]; 20 | if (self != nil) { 21 | error_ = nil; 22 | result_ = nil; 23 | deferred_ = [[HLDeferred alloc] initWithCanceller: self]; 24 | } 25 | return self; 26 | } 27 | 28 | - (void) dealloc 29 | { 30 | [error_ release]; error_ = nil; 31 | [result_ release]; result_ = nil; 32 | [deferred_ setCanceller: nil]; 33 | [deferred_ release]; deferred_ = nil; 34 | [callingThread_ release]; callingThread_ = nil; 35 | [super dealloc]; 36 | } 37 | 38 | - (NSThread *) actualCallingThread 39 | { 40 | NSThread *result = [self callingThread]; 41 | if (result == nil) result = [NSThread mainThread]; 42 | return result; 43 | } 44 | 45 | - (BOOL) isActualCallingThread 46 | { 47 | return ([self callingThread] == nil) || [[NSThread currentThread] isEqual: [self actualCallingThread]]; 48 | } 49 | 50 | - (HLDeferred *) requestStartOnQueue: (NSOperationQueue *)queue 51 | { 52 | @synchronized (self) { 53 | // setting callingThread before requestStartOnQueue 54 | // lets you choose the thread that the result 55 | // will be delivered on 56 | if ([self callingThread] == nil) { 57 | [self setCallingThread: [NSThread currentThread]]; 58 | } 59 | [queue addOperation: self]; 60 | return [[deferred_ retain] autorelease]; 61 | } 62 | } 63 | 64 | // DO NOT OVERRIDE THIS METHOD 65 | // DO NOT OVERRIDE -start EITHER 66 | // override -execute instead 67 | // called on the queue's thread 68 | - (void) main 69 | { 70 | @try { 71 | [self execute]; 72 | } @catch (NSException * e) { 73 | [self setError: e]; 74 | [self asyncCompleteOperationError]; 75 | } 76 | } 77 | 78 | // override this method in your subclass to perform work 79 | // called on the queue's thread 80 | - (void) execute {} 81 | 82 | #pragma mark - 83 | #pragma mark Completing the data source's operation 84 | 85 | - (void) cancel 86 | { 87 | [super cancel]; 88 | if ([self isExecuting]) { 89 | [self setError: kHLDeferredCancelled]; 90 | [self asyncCompleteOperationError]; 91 | } 92 | } 93 | 94 | // overridden by HLDeferredConcurrentDataSource 95 | // called on the callingThread 96 | - (void) markOperationCompleted {} 97 | 98 | - (void) asyncCompleteOperationResult 99 | { 100 | [self performSelector: @selector(asyncCompleteOperationResultOnCallingThread) 101 | onThread: [self actualCallingThread] 102 | withObject: nil 103 | waitUntilDone: NO]; 104 | } 105 | 106 | - (void) asyncCompleteOperationResultOnCallingThread 107 | { 108 | assert([self isActualCallingThread]); 109 | [deferred_ takeResult: [[result_ retain] autorelease]]; 110 | [self markOperationCompleted]; 111 | } 112 | 113 | - (void) asyncCompleteOperationError 114 | { 115 | [self performSelector: @selector(asyncCompleteOperationErrorOnCallingThread) 116 | onThread: [self actualCallingThread] 117 | withObject: nil 118 | waitUntilDone: NO]; 119 | } 120 | 121 | - (void) asyncCompleteOperationErrorOnCallingThread 122 | { 123 | assert([self isActualCallingThread]); 124 | [deferred_ takeError: [[error_ retain] autorelease]]; 125 | [self markOperationCompleted]; 126 | } 127 | 128 | - (void) deferredWillCancel: (HLDeferred *)d 129 | { 130 | [self cancel]; 131 | } 132 | 133 | @end 134 | -------------------------------------------------------------------------------- /HLDeferred/Tests/HLJSONDataSourceTest.m: -------------------------------------------------------------------------------- 1 | // 2 | // HLJSONDataSourceTest.m 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLJSONDataSource.h" 10 | #import "JSONKit.h" 11 | 12 | @interface HLJSONDataSourceTest : GHAsyncTestCase 13 | @end 14 | 15 | @implementation HLJSONDataSourceTest 16 | 17 | - (void) testEmptyStringToJSONKit 18 | { 19 | NSError *error = nil; 20 | id result = [@"" objectFromJSONStringWithParseOptions: JKParseOptionStrict error: &error]; 21 | GHAssertNil(result, @"expected nil back when parsing empty string"); 22 | GHAssertNotNil(error, @"expected error when parsing empty string: %@", error); 23 | error = nil; 24 | result = [@"null" objectFromJSONStringWithParseOptions: JKParseOptionStrict error: &error]; 25 | GHAssertNil(result, @"expected nil back when parsing \"null\""); 26 | // i don't really want this error, but it's not working, so i want to know if this 27 | // behaviour changes in the future. 28 | GHAssertNotNil(error, @"expected error when parsing \"null\" string: %@", error); 29 | } 30 | 31 | - (void) testSimple 32 | { 33 | [self prepare]; 34 | 35 | HLJSONDataSource *ds = [[HLJSONDataSource alloc] initWithURLString: @"http://graph.facebook.com/19292868552"]; 36 | HLDeferred *d = [ds requestStartOnQueue: [NSOperationQueue mainQueue]]; 37 | [ds release]; ds = nil; 38 | 39 | __block BOOL success = NO; 40 | __block id theResult = nil; 41 | [d then: ^(id result) { 42 | success = YES; 43 | theResult = [result retain]; 44 | [self notify: kGHUnitWaitStatusSuccess forSelector: @selector(testSimple)]; 45 | return result; 46 | } fail: ^(HLFailure *failure) { 47 | [self notify: kGHUnitWaitStatusFailure forSelector: @selector(testSimple)]; 48 | return failure; 49 | }]; 50 | [self waitForStatus: kGHUnitWaitStatusSuccess timeout: 10.0]; 51 | GHAssertTrue(success, @"callback didn't run"); 52 | GHAssertNotNil(theResult, nil); 53 | GHAssertTrue([theResult isKindOfClass: [NSDictionary class]], @"theResult is a %@, not NSDictionary", NSStringFromClass([theResult class])); 54 | [theResult release]; 55 | } 56 | 57 | - (void) testFail 58 | { 59 | [self prepare]; 60 | 61 | HLJSONDataSource *ds = [[HLJSONDataSource alloc] initWithURLString: @"http://www.google.com/"]; 62 | HLDeferred *d = [ds requestStartOnQueue: [NSOperationQueue mainQueue]]; 63 | [ds release]; ds = nil; 64 | 65 | __block BOOL success = NO; 66 | 67 | [d then: ^(id result) { 68 | [self notify: kGHUnitWaitStatusFailure forSelector: @selector(testFail)]; 69 | return result; 70 | } fail: ^(HLFailure *failure) { 71 | success = YES; 72 | [self notify: kGHUnitWaitStatusSuccess forSelector: @selector(testFail)]; 73 | return failure; 74 | }]; 75 | [self waitForStatus: kGHUnitWaitStatusSuccess timeout: 5.0]; 76 | GHAssertTrue(success, @"errback didn't run"); 77 | } 78 | 79 | - (void) testNotFound 80 | { 81 | [self prepare]; 82 | 83 | HLJSONDataSource *ds = [[HLJSONDataSource alloc] initWithURLString: @"http://www.google.com/asdfasdfasdf"]; 84 | HLDeferred *d = [ds requestStartOnQueue: [NSOperationQueue mainQueue]]; 85 | [ds release]; ds = nil; 86 | 87 | __block BOOL success = NO; 88 | __block id theResult = nil; 89 | 90 | [d then: ^(id result) { 91 | success = YES; 92 | theResult = [result retain]; 93 | [self notify: kGHUnitWaitStatusSuccess forSelector: @selector(testNotFound)]; 94 | return result; 95 | } fail: ^(HLFailure *failure) { 96 | [self notify: kGHUnitWaitStatusFailure forSelector: @selector(testNotFound)]; 97 | return failure; 98 | }]; 99 | [self waitForStatus: kGHUnitWaitStatusSuccess timeout: 5.0]; 100 | GHAssertTrue(success, @"callback didn't run"); 101 | GHAssertNil(theResult, nil); 102 | [theResult release]; theResult = nil; 103 | } 104 | 105 | @end 106 | -------------------------------------------------------------------------------- /HLDeferred/Classes/HLDeferredConcurrentDataSource.m: -------------------------------------------------------------------------------- 1 | // 2 | // HLDeferredConcurrentDataSource.m 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLDeferredConcurrentDataSource.h" 10 | 11 | @implementation HLDeferredConcurrentDataSource 12 | 13 | @synthesize runLoopThread=runLoopThread_; 14 | @synthesize runLoopModes=runLoopModes_; 15 | 16 | - (id) init 17 | { 18 | self = [super init]; 19 | if (self != nil) { 20 | executing_ = NO; 21 | finished_ = NO; 22 | } 23 | return self; 24 | } 25 | 26 | - (void) dealloc 27 | { 28 | [runLoopThread_ release]; runLoopThread_ = nil; 29 | [runLoopModes_ release]; runLoopModes_ = nil; 30 | [super dealloc]; 31 | } 32 | 33 | - (NSThread *) actualRunLoopThread 34 | { 35 | NSThread *result = [self runLoopThread]; 36 | if (result == nil) result = [NSThread mainThread]; 37 | return result; 38 | } 39 | 40 | - (BOOL) isActualRunLoopThread 41 | { 42 | return [[NSThread currentThread] isEqual: [self actualRunLoopThread]]; 43 | } 44 | 45 | - (NSSet *) actualRunLoopModes 46 | { 47 | NSSet * result = [self runLoopModes]; 48 | if ( (result == nil) || ([result count] == 0) ) { 49 | result = [NSSet setWithObject: NSDefaultRunLoopMode]; 50 | } 51 | return result; 52 | } 53 | 54 | #pragma mark - 55 | #pragma mark HLDeferred support 56 | 57 | // called on the callingThread 58 | - (void) markOperationCompleted 59 | { 60 | assert([self isActualCallingThread]); 61 | [self willChangeValueForKey: @"isFinished"]; 62 | [self willChangeValueForKey: @"isExecuting"]; 63 | 64 | executing_ = NO; 65 | finished_ = YES; 66 | 67 | [self didChangeValueForKey: @"isExecuting"]; 68 | [self didChangeValueForKey: @"isFinished"]; 69 | } 70 | 71 | #pragma mark - 72 | #pragma mark Concurrent NSOperation support 73 | 74 | - (BOOL) isConcurrent { return YES; } 75 | - (BOOL) isExecuting { return executing_; } 76 | - (BOOL) isFinished { return finished_; } 77 | 78 | // DO NOT OVERRIDE THIS METHOD 79 | // override -execute instead 80 | // called on the queue's thread 81 | - (void) start 82 | { 83 | if ([self isCancelled]) { 84 | [self willChangeValueForKey: @"isFinished"]; 85 | finished_ = YES; 86 | [self didChangeValueForKey: @"isFinished"]; 87 | [self setError: kHLDeferredCancelled]; 88 | [self asyncCompleteOperationError]; 89 | } else { 90 | [self main]; 91 | } 92 | } 93 | 94 | // DO NOT OVERRIDE THIS METHOD 95 | // override -execute instead 96 | // called on the queue's thread 97 | - (void) main 98 | { 99 | [self willChangeValueForKey: @"isExecuting"]; 100 | executing_ = YES; 101 | [self didChangeValueForKey: @"isExecuting"]; 102 | 103 | [self performSelector: @selector(executeOnRunLoopThread) 104 | onThread: [self actualRunLoopThread] 105 | withObject: nil 106 | waitUntilDone: NO 107 | modes: [[self actualRunLoopModes] allObjects]]; 108 | } 109 | 110 | - (void) executeOnRunLoopThread 111 | { 112 | assert([self isActualRunLoopThread]); 113 | NSException *thrown = nil; 114 | @try { 115 | [self execute]; 116 | } @catch (NSException *e) { 117 | thrown = e; 118 | } 119 | if (thrown) { 120 | [self setError: thrown]; 121 | [self asyncCompleteOperationError]; 122 | } 123 | } 124 | 125 | // override this method to perform work 126 | // called on the queue's thread 127 | - (void) execute 128 | { 129 | [super execute]; 130 | } 131 | 132 | #pragma mark - 133 | #pragma mark HLDeferred support 134 | 135 | // NO NOT OVERRIDE THIS 136 | // override cancelOnRunLoopThread instead 137 | - (void) cancel 138 | { 139 | // THIS IS SYNCHRONOUS 140 | [self performSelector: @selector(cancelOnRunLoopThread) 141 | onThread: [self actualRunLoopThread] 142 | withObject: nil 143 | waitUntilDone: YES // <--- SYNCHRONOUS 144 | modes: [[self actualRunLoopModes] allObjects]]; 145 | } 146 | 147 | - (void) cancelOnRunLoopThread 148 | { 149 | assert([self isActualRunLoopThread]); 150 | [super cancel]; 151 | } 152 | 153 | @end 154 | -------------------------------------------------------------------------------- /HLDeferred/Classes/HLDeferredList.m: -------------------------------------------------------------------------------- 1 | // 2 | // HLDeferredList.m 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLDeferredList.h" 10 | 11 | NSString * const kHLDeferredListNilSentinel = @"__HLDeferredListNilSentinel__"; 12 | 13 | @implementation HLDeferredList 14 | 15 | - (id) initWithDeferreds: (NSArray *)list 16 | fireOnFirstResult: (BOOL)flFireOnFirstResult 17 | fireOnFirstError: (BOOL)flFireOnFirstError 18 | consumeErrors: (BOOL)flConsumeErrors 19 | { 20 | self = [super init]; 21 | if (self) { 22 | deferreds_ = [(list ? list : [NSArray array]) copy]; 23 | fireOnFirstResult_ = flFireOnFirstResult; 24 | fireOnFirstError_ = flFireOnFirstError; 25 | consumeErrors_ = flConsumeErrors; 26 | results_ = [[NSMutableArray alloc] initWithCapacity: [list count]]; 27 | finishedCount_ = 0; 28 | cancelDeferredsWhenCancelled_ = NO; 29 | 30 | int i; 31 | for (i = 0; i < [deferreds_ count]; i++) { 32 | [results_ addObject: [NSNull null]]; 33 | } 34 | 35 | if (([deferreds_ count] == 0) && (!fireOnFirstResult_)) { 36 | [self takeResult: results_]; 37 | } 38 | 39 | [deferreds_ enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) { 40 | __block ThenBlock deferredCallback = ^(id result) { 41 | if ([result isKindOfClass: [HLDeferred class]]) { 42 | [result both: deferredCallback]; 43 | return result; 44 | }; 45 | [results_ replaceObjectAtIndex: idx withObject: result ? result : [NSNull null]]; 46 | ++finishedCount_; 47 | BOOL succeeded = ![result isKindOfClass: [HLFailure class]]; 48 | if (![self isCalled]) { 49 | if (succeeded && fireOnFirstResult_) 50 | [self takeResult: result]; 51 | else if (!succeeded && fireOnFirstError_) 52 | [self takeError: result]; 53 | else if (finishedCount_ == [results_ count]) 54 | [self takeResult: results_]; 55 | } 56 | 57 | if ((!succeeded) && consumeErrors_) { 58 | result = nil; 59 | } 60 | return result; 61 | }; 62 | [obj both: deferredCallback]; 63 | }]; 64 | } 65 | return self; 66 | } 67 | 68 | - (id) initWithDeferreds: (NSArray *)list 69 | { 70 | self = [self initWithDeferreds: list 71 | fireOnFirstResult: NO 72 | fireOnFirstError: NO 73 | consumeErrors: NO]; 74 | return self; 75 | } 76 | 77 | - (id) initWithDeferreds: (NSArray *)list fireOnFirstResult: (BOOL)flFireOnFirstResult 78 | { 79 | self = [self initWithDeferreds: list 80 | fireOnFirstResult: flFireOnFirstResult 81 | fireOnFirstError: NO 82 | consumeErrors: NO]; 83 | return self; 84 | } 85 | 86 | - (id) initWithDeferreds: (NSArray *)list fireOnFirstResult: (BOOL)flFireOnFirstResult consumeErrors: (BOOL)flConsumeErrors 87 | { 88 | self = [self initWithDeferreds: list 89 | fireOnFirstResult: flFireOnFirstResult 90 | fireOnFirstError: NO 91 | consumeErrors: flConsumeErrors]; 92 | return self; 93 | } 94 | 95 | - (id) initWithDeferreds: (NSArray *)list fireOnFirstError: (BOOL)flFireOnFirstError 96 | { 97 | self = [self initWithDeferreds: list 98 | fireOnFirstResult: NO 99 | fireOnFirstError: flFireOnFirstError 100 | consumeErrors: NO]; 101 | return self; 102 | } 103 | 104 | - (id) initWithDeferreds: (NSArray *)list consumeErrors: (BOOL)flConsumeErrors 105 | { 106 | self = [self initWithDeferreds: list 107 | fireOnFirstResult: NO 108 | fireOnFirstError: NO 109 | consumeErrors: flConsumeErrors]; 110 | return self; 111 | } 112 | 113 | - (void) dealloc 114 | { 115 | [deferreds_ release]; deferreds_ = nil; 116 | [results_ release]; results_ = nil; 117 | [super dealloc]; 118 | } 119 | 120 | - (void) cancelDeferredsWhenCancelled 121 | { 122 | cancelDeferredsWhenCancelled_ = YES; 123 | } 124 | 125 | - (void) cancel 126 | { 127 | [super cancel]; 128 | if (cancelDeferredsWhenCancelled_) { 129 | [deferreds_ makeObjectsPerformSelector: @selector(cancel)]; 130 | } 131 | } 132 | 133 | @end 134 | -------------------------------------------------------------------------------- /HLDeferred/Classes/HLDeferredDataSourceManager.m: -------------------------------------------------------------------------------- 1 | // 2 | // HLDeferredDataSourceManager.m 3 | // HLDeferred 4 | // 5 | // Created by Jim Roepcke on 11-07-10. 6 | // Copyright 2011 Jim Roepcke. All rights reserved. 7 | // See included LICENSE file (MIT) for licensing information. 8 | // 9 | 10 | // This code is based on NetworkManager from MVCNetworking sample 11 | 12 | #import "HLDeferredDataSourceManager.h" 13 | #import "HLDeferredDataSource.h" 14 | #import "HLDeferredConcurrentDataSource.h" 15 | 16 | @interface HLDeferredDataSourceManager () 17 | 18 | // private properties 19 | 20 | @property (nonatomic, readonly, retain ) NSThread *networkRunLoopThread; 21 | @property (nonatomic, readonly, retain ) NSOperationQueue *queueForNetworkTransfers; 22 | 23 | @end 24 | 25 | @implementation HLDeferredDataSourceManager 26 | 27 | @synthesize networkRunLoopThread=_networkRunLoopThread; 28 | @synthesize queueForNetworkTransfers=_queueForNetworkTransfers; 29 | 30 | - (id) initWithRunLoopThreadName: (NSString *)name 31 | { 32 | self = [super init]; 33 | if (self) { 34 | 35 | // Create the network transfer queue. We will run up to 4 simultaneous network requests. 36 | 37 | _queueForNetworkTransfers = [[NSOperationQueue alloc] init]; 38 | assert(_queueForNetworkTransfers != nil); 39 | 40 | [_queueForNetworkTransfers setMaxConcurrentOperationCount: 4]; 41 | assert(_queueForNetworkTransfers != nil); 42 | 43 | // We run all of our network callbacks on a secondary thread to ensure that they don't 44 | // contribute to main thread latency. Create and configure that thread. 45 | 46 | // this retains self, so now we have a retain loop. fantastic 47 | _networkRunLoopThreadContinue = YES; 48 | _networkRunLoopThread = [[NSThread alloc] initWithTarget: self 49 | selector: @selector(networkRunLoopThreadEntry) 50 | object: nil]; 51 | assert(_networkRunLoopThread != nil); 52 | 53 | [_networkRunLoopThread setName: name]; 54 | if ( [_networkRunLoopThread respondsToSelector: @selector(setThreadPriority)] ) { 55 | [_networkRunLoopThread setThreadPriority: 0.3]; 56 | } 57 | 58 | [_networkRunLoopThread start]; 59 | } 60 | return self; 61 | } 62 | 63 | - (void) dealloc 64 | { 65 | // this cannot run until the _networkRunLoopThread is terminated 66 | // because it retains self 67 | [_queueForNetworkTransfers cancelAllOperations]; 68 | [_queueForNetworkTransfers release]; _queueForNetworkTransfers = nil; 69 | [_networkRunLoopThread release]; _networkRunLoopThread = nil; 70 | [super dealloc]; 71 | } 72 | 73 | - (void) stop: (HLVoidBlock)completion 74 | { 75 | HLVoidBlock completionBlock = (HLVoidBlock)[completion copy]; 76 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 77 | [_queueForNetworkTransfers cancelAllOperations]; 78 | [_queueForNetworkTransfers waitUntilAllOperationsAreFinished]; 79 | [self performSelector: @selector(networkRunLoopThreadStopper) 80 | onThread: _networkRunLoopThread 81 | withObject: nil 82 | waitUntilDone: YES]; 83 | completionBlock(); 84 | [completionBlock release]; 85 | }); 86 | } 87 | 88 | // this gets the run loop to run so that the _networkRunLoopThread's 89 | // -[[NSRunLoop currentRunLoop] runMode:beforeDate:] finishes 90 | // and the thread can exit 91 | - (void) networkRunLoopThreadStopper { 92 | _networkRunLoopThreadContinue = NO; 93 | } 94 | 95 | - (void) networkRunLoopThreadEntry 96 | { 97 | assert( ! [NSThread isMainThread] ); 98 | while (_networkRunLoopThreadContinue) { 99 | NSAutoreleasePool * pool; 100 | 101 | pool = [[NSAutoreleasePool alloc] init]; 102 | assert(pool != nil); 103 | 104 | [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate: [NSDate distantFuture]]; 105 | 106 | [pool drain]; 107 | } 108 | } 109 | 110 | - (BOOL) networkInUse 111 | { 112 | assert([NSThread isMainThread]); 113 | return _runningNetworkTransferCount != 0; 114 | } 115 | 116 | - (void) incrementRunningNetworkTransferCount 117 | { 118 | assert([NSThread isMainThread]); 119 | 120 | BOOL movingToInUse = (_runningNetworkTransferCount == 0); 121 | 122 | if (movingToInUse) [self willChangeValueForKey: @"networkInUse"]; 123 | _runningNetworkTransferCount += 1; 124 | if (movingToInUse) [self didChangeValueForKey: @"networkInUse"]; 125 | } 126 | 127 | - (void) decrementRunningNetworkTransferCount 128 | { 129 | assert([NSThread isMainThread]); 130 | 131 | assert(_runningNetworkTransferCount != 0); 132 | BOOL movingToNotInUse = (_runningNetworkTransferCount == 1); 133 | if (movingToNotInUse) [self willChangeValueForKey: @"networkInUse"]; 134 | _runningNetworkTransferCount -= 1; 135 | if (movingToNotInUse) [self didChangeValueForKey: @"networkInUse"]; 136 | } 137 | 138 | - (HLDeferred *) requestStartNetworkTransferDataSource: (HLDeferredDataSource *)ds 139 | { 140 | __block HLDeferredDataSourceManager *blockSelf = self; 141 | if ([ds respondsToSelector: @selector(setRunLoopThread:)]) { 142 | // this is a concurrent data source, give it a runLoopThread 143 | // this keeps network processing off the main thread which 144 | // improves UI responsiveness 145 | [(id)ds setRunLoopThread: [self networkRunLoopThread]]; 146 | } 147 | HLDeferred *result = [ds requestStartOnQueue: [self queueForNetworkTransfers]]; 148 | [self performSelectorOnMainThread: @selector(incrementRunningNetworkTransferCount) 149 | withObject: nil 150 | waitUntilDone: NO]; 151 | result = [result both: ^(id result) { 152 | [blockSelf performSelectorOnMainThread: @selector(decrementRunningNetworkTransferCount) 153 | withObject: nil 154 | waitUntilDone: NO]; 155 | return result; 156 | }]; 157 | return result; 158 | } 159 | 160 | @end 161 | -------------------------------------------------------------------------------- /HLDeferred/Classes/HLURLDataSource.m: -------------------------------------------------------------------------------- 1 | // 2 | // HLURLDataSource.m 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLURLDataSource.h" 10 | 11 | @implementation HLURLDataSource 12 | 13 | @synthesize context=context_; 14 | @synthesize responseData=responseData_; 15 | 16 | + (HLURLDataSource *) postToURL: (NSURL *)url 17 | withBody: (NSString *)body 18 | { 19 | return [[[HLURLDataSource alloc] initWithContext: [NSDictionary dictionaryWithObjectsAndKeys: 20 | @"POST", @"requestMethod", 21 | url, @"requestURL", 22 | body, @"requestBody", nil]] autorelease]; 23 | } 24 | 25 | - (id) initWithContext: (NSDictionary *)aContext 26 | { 27 | self = [super init]; 28 | if (self) { 29 | conn_ = nil; 30 | response_ = nil; 31 | responseData_ = nil; 32 | context_ = [aContext retain]; 33 | } 34 | return self; 35 | } 36 | 37 | - (id) initWithURL: (NSURL *)url 38 | { 39 | self = [self initWithContext: [NSDictionary dictionaryWithObject: url forKey: @"requestURL"]]; 40 | return self; 41 | } 42 | 43 | - (id) initWithURLString: (NSString *)urlString 44 | { 45 | self = [self initWithContext: [NSDictionary dictionaryWithObject: urlString forKey: @"requestURL"]]; 46 | return self; 47 | } 48 | 49 | - (void) dealloc 50 | { 51 | [conn_ release]; conn_ = nil; 52 | [response_ release]; response_ = nil; 53 | [responseData_ release]; responseData_ = nil; 54 | [context_ release]; context_ = nil; 55 | [super dealloc]; 56 | } 57 | 58 | #pragma mark - 59 | #pragma mark Public API: template methods, override these to customize behaviour 60 | 61 | - (NSMutableURLRequest *) urlRequest 62 | { 63 | NSMutableURLRequest *result = nil; 64 | id requestURL = [context_ objectForKey: @"requestURL"]; 65 | if (requestURL) { 66 | if ([requestURL isKindOfClass: [NSString class]]) { 67 | requestURL = [NSURL URLWithString: requestURL]; 68 | } 69 | result = [NSMutableURLRequest requestWithURL: requestURL 70 | cachePolicy: NSURLRequestReloadIgnoringLocalCacheData 71 | timeoutInterval: 240.0]; 72 | // allow response to be gzip compressed 73 | [result setValue: @"gzip" forHTTPHeaderField: @"Accept-Encoding"]; 74 | NSString *requestMethod = [context_ objectForKey: @"requestMethod"]; 75 | [result setHTTPMethod: requestMethod ? requestMethod : @"GET"]; 76 | NSData *requestBody = [context_ objectForKey: @"requestBody"]; 77 | if (requestBody) { 78 | [result setHTTPBody: requestBody]; 79 | [result setValue: [NSString stringWithFormat: @"%d", [requestBody length]] forHTTPHeaderField: @"Content-Length"]; 80 | } 81 | NSString *requestBodyContentType = [context_ objectForKey: @"requestBodyContentType"]; 82 | if (requestBodyContentType) [result setValue: requestBodyContentType forHTTPHeaderField: @"content-type"]; 83 | NSString *lastModified = [context_ objectForKey: @"requestIfModifiedSince"]; 84 | if (lastModified) [result setValue: lastModified forHTTPHeaderField: @"If-Modified-Since"]; 85 | } 86 | return result; 87 | } 88 | 89 | - (void) execute 90 | { 91 | [conn_ release]; 92 | conn_ = [[NSURLConnection alloc] initWithRequest: [self urlRequest] 93 | delegate: self]; 94 | } 95 | 96 | - (void) cancelOnRunLoopThread 97 | { 98 | [conn_ cancel]; 99 | [super cancelOnRunLoopThread]; 100 | } 101 | 102 | - (void) responseFailed 103 | { 104 | [self asyncCompleteOperationError]; 105 | } 106 | 107 | - (BOOL) responseBegan 108 | { 109 | BOOL result = NO; 110 | if ([response_ isKindOfClass: [NSHTTPURLResponse class]]) { 111 | NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response_; 112 | NSInteger statusCode = [httpResponse statusCode]; 113 | if ((statusCode >= 200) && (statusCode < 300)) { 114 | [responseData_ release]; 115 | responseData_ = [[NSMutableData alloc] init]; // YAY! 116 | result = YES; 117 | } 118 | } else { 119 | [responseData_ release]; 120 | responseData_ = [[NSMutableData alloc] init]; // YAY! 121 | result = YES; 122 | } 123 | return result; 124 | } 125 | 126 | - (void) responseReceivedData: (NSData *)data 127 | { 128 | if (responseData_) { 129 | [responseData_ appendData: data]; 130 | } 131 | } 132 | 133 | - (void) responseFinished 134 | { 135 | [self asyncCompleteOperationResult]; 136 | } 137 | 138 | #pragma mark - 139 | #pragma mark Private API 140 | 141 | - (void) connection: (NSURLConnection *)connection didFailWithError: (NSError *)anError 142 | { 143 | [self setError: anError]; 144 | [self responseFailed]; 145 | } 146 | 147 | - (void) connection: (NSURLConnection *)connection didReceiveResponse: (NSURLResponse *)aResponse 148 | { 149 | [response_ release]; 150 | response_ = [aResponse retain]; 151 | [self responseBegan]; 152 | } 153 | 154 | - (void) connection: (NSURLConnection *)connection didReceiveData: (NSData *)data 155 | { 156 | [self responseReceivedData: data]; 157 | } 158 | 159 | - (void) connectionDidFinishLoading: (NSURLConnection *)connection 160 | { 161 | [self setResult: responseData_]; 162 | [self responseFinished]; 163 | } 164 | 165 | #pragma mark - 166 | #pragma mark Public API 167 | 168 | - (NSString *) responseHeaderValueForKey: (NSString *)key 169 | { 170 | if ([response_ isKindOfClass: [NSHTTPURLResponse class]]) { 171 | NSHTTPURLResponse *r = (NSHTTPURLResponse *)response_; 172 | return [[r allHeaderFields] objectForKey: key]; 173 | } 174 | return nil; 175 | } 176 | 177 | - (NSInteger) responseStatusCode 178 | { 179 | NSInteger result = 0; 180 | if ([response_ isKindOfClass: [NSHTTPURLResponse class]]) { 181 | NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response_; 182 | result = [httpResponse statusCode]; 183 | } 184 | return result; 185 | } 186 | 187 | - (BOOL) entityWasOK 188 | { 189 | return [self responseStatusCode] == 200; 190 | } 191 | 192 | - (BOOL) entityWasNotModified 193 | { 194 | return [self responseStatusCode] == 304; 195 | } 196 | 197 | - (BOOL) entityWasNotFound 198 | { 199 | return [self responseStatusCode] == 404; 200 | } 201 | 202 | @end 203 | -------------------------------------------------------------------------------- /HLDeferred/Classes/JSONKit.h: -------------------------------------------------------------------------------- 1 | // 2 | // JSONKit.h 3 | // http://github.com/johnezang/JSONKit 4 | // Dual licensed under either the terms of the BSD License, or alternatively 5 | // under the terms of the Apache License, Version 2.0, as specified below. 6 | // 7 | 8 | /* 9 | Copyright (c) 2011, John Engelhart 10 | 11 | All rights reserved. 12 | 13 | Redistribution and use in source and binary forms, with or without 14 | modification, are permitted provided that the following conditions are met: 15 | 16 | * Redistributions of source code must retain the above copyright 17 | notice, this list of conditions and the following disclaimer. 18 | 19 | * Redistributions in binary form must reproduce the above copyright 20 | notice, this list of conditions and the following disclaimer in the 21 | documentation and/or other materials provided with the distribution. 22 | 23 | * Neither the name of the Zang Industries nor the names of its 24 | contributors may be used to endorse or promote products derived from 25 | this software without specific prior written permission. 26 | 27 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 28 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 29 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 30 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 31 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 32 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 33 | TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 34 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 35 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 36 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 37 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 38 | */ 39 | 40 | /* 41 | Copyright 2011 John Engelhart 42 | 43 | Licensed under the Apache License, Version 2.0 (the "License"); 44 | you may not use this file except in compliance with the License. 45 | You may obtain a copy of the License at 46 | 47 | http://www.apache.org/licenses/LICENSE-2.0 48 | 49 | Unless required by applicable law or agreed to in writing, software 50 | distributed under the License is distributed on an "AS IS" BASIS, 51 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 52 | See the License for the specific language governing permissions and 53 | limitations under the License. 54 | */ 55 | 56 | #include 57 | #include 58 | #include 59 | #include 60 | #include 61 | 62 | #ifdef __OBJC__ 63 | #import 64 | #import 65 | #import 66 | #import 67 | #import 68 | #import 69 | #endif // __OBJC__ 70 | 71 | #ifdef __cplusplus 72 | extern "C" { 73 | #endif 74 | 75 | 76 | // For Mac OS X < 10.5. 77 | #ifndef NSINTEGER_DEFINED 78 | #define NSINTEGER_DEFINED 79 | #if defined(__LP64__) || defined(NS_BUILD_32_LIKE_64) 80 | typedef long NSInteger; 81 | typedef unsigned long NSUInteger; 82 | #define NSIntegerMin LONG_MIN 83 | #define NSIntegerMax LONG_MAX 84 | #define NSUIntegerMax ULONG_MAX 85 | #else // defined(__LP64__) || defined(NS_BUILD_32_LIKE_64) 86 | typedef int NSInteger; 87 | typedef unsigned int NSUInteger; 88 | #define NSIntegerMin INT_MIN 89 | #define NSIntegerMax INT_MAX 90 | #define NSUIntegerMax UINT_MAX 91 | #endif // defined(__LP64__) || defined(NS_BUILD_32_LIKE_64) 92 | #endif // NSINTEGER_DEFINED 93 | 94 | 95 | #ifndef _JSONKIT_H_ 96 | #define _JSONKIT_H_ 97 | 98 | #if defined(__GNUC__) && (__GNUC__ >= 4) && defined(__APPLE_CC__) && (__APPLE_CC__ >= 5465) 99 | #define JK_DEPRECATED_ATTRIBUTE __attribute__((deprecated)) 100 | #else 101 | #define JK_DEPRECATED_ATTRIBUTE 102 | #endif 103 | 104 | #define JSONKIT_VERSION_MAJOR 1 105 | #define JSONKIT_VERSION_MINOR 4 106 | 107 | typedef NSUInteger JKFlags; 108 | 109 | /* 110 | JKParseOptionComments : Allow C style // and /_* ... *_/ (without a _, obviously) comments in JSON. 111 | JKParseOptionUnicodeNewlines : Allow Unicode recommended (?:\r\n|[\n\v\f\r\x85\p{Zl}\p{Zp}]) newlines. 112 | JKParseOptionLooseUnicode : Normally the decoder will stop with an error at any malformed Unicode. 113 | This option allows JSON with malformed Unicode to be parsed without reporting an error. 114 | Any malformed Unicode is replaced with \uFFFD, or "REPLACEMENT CHARACTER". 115 | */ 116 | 117 | enum { 118 | JKParseOptionNone = 0, 119 | JKParseOptionStrict = 0, 120 | JKParseOptionComments = (1 << 0), 121 | JKParseOptionUnicodeNewlines = (1 << 1), 122 | JKParseOptionLooseUnicode = (1 << 2), 123 | JKParseOptionPermitTextAfterValidJSON = (1 << 3), 124 | JKParseOptionValidFlags = (JKParseOptionComments | JKParseOptionUnicodeNewlines | JKParseOptionLooseUnicode | JKParseOptionPermitTextAfterValidJSON), 125 | }; 126 | typedef JKFlags JKParseOptionFlags; 127 | 128 | enum { 129 | JKSerializeOptionNone = 0, 130 | JKSerializeOptionPretty = (1 << 0), 131 | JKSerializeOptionEscapeUnicode = (1 << 1), 132 | JKSerializeOptionEscapeForwardSlashes = (1 << 4), 133 | JKSerializeOptionValidFlags = (JKSerializeOptionPretty | JKSerializeOptionEscapeUnicode | JKSerializeOptionEscapeForwardSlashes), 134 | }; 135 | typedef JKFlags JKSerializeOptionFlags; 136 | 137 | #ifdef __OBJC__ 138 | 139 | typedef struct JKParseState JKParseState; // Opaque internal, private type. 140 | 141 | // As a general rule of thumb, if you use a method that doesn't accept a JKParseOptionFlags argument, it defaults to JKParseOptionStrict 142 | 143 | @interface JSONDecoder : NSObject { 144 | JKParseState *parseState; 145 | } 146 | + (id)decoder; 147 | + (id)decoderWithParseOptions:(JKParseOptionFlags)parseOptionFlags; 148 | - (id)initWithParseOptions:(JKParseOptionFlags)parseOptionFlags; 149 | - (void)clearCache; 150 | 151 | // The parse... methods were deprecated in v1.4 in favor of the v1.4 objectWith... methods. 152 | - (id)parseUTF8String:(const unsigned char *)string length:(size_t)length JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithUTF8String:length: instead. 153 | - (id)parseUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithUTF8String:length:error: instead. 154 | // The NSData MUST be UTF8 encoded JSON. 155 | - (id)parseJSONData:(NSData *)jsonData JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithData: instead. 156 | - (id)parseJSONData:(NSData *)jsonData error:(NSError **)error JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithData:error: instead. 157 | 158 | // Methods that return immutable collection objects. 159 | - (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length; 160 | - (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error; 161 | // The NSData MUST be UTF8 encoded JSON. 162 | - (id)objectWithData:(NSData *)jsonData; 163 | - (id)objectWithData:(NSData *)jsonData error:(NSError **)error; 164 | 165 | // Methods that return mutable collection objects. 166 | - (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length; 167 | - (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error; 168 | // The NSData MUST be UTF8 encoded JSON. 169 | - (id)mutableObjectWithData:(NSData *)jsonData; 170 | - (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error; 171 | 172 | @end 173 | 174 | //////////// 175 | #pragma mark Deserializing methods 176 | //////////// 177 | 178 | @interface NSString (JSONKitDeserializing) 179 | - (id)objectFromJSONString; 180 | - (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags; 181 | - (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error; 182 | - (id)mutableObjectFromJSONString; 183 | - (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags; 184 | - (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error; 185 | @end 186 | 187 | @interface NSData (JSONKitDeserializing) 188 | // The NSData MUST be UTF8 encoded JSON. 189 | - (id)objectFromJSONData; 190 | - (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags; 191 | - (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error; 192 | - (id)mutableObjectFromJSONData; 193 | - (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags; 194 | - (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error; 195 | @end 196 | 197 | //////////// 198 | #pragma mark Serializing methods 199 | //////////// 200 | 201 | @interface NSString (JSONKitSerializing) 202 | // Convenience methods for those that need to serialize the receiving NSString (i.e., instead of having to serialize a NSArray with a single NSString, you can "serialize to JSON" just the NSString). 203 | // Normally, a string that is serialized to JSON has quotation marks surrounding it, which you may or may not want when serializing a single string, and can be controlled with includeQuotes: 204 | // includeQuotes:YES `a "test"...` -> `"a \"test\"..."` 205 | // includeQuotes:NO `a "test"...` -> `a \"test\"...` 206 | - (NSData *)JSONData; // Invokes JSONDataWithOptions:JKSerializeOptionNone includeQuotes:YES 207 | - (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error; 208 | - (NSString *)JSONString; // Invokes JSONStringWithOptions:JKSerializeOptionNone includeQuotes:YES 209 | - (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error; 210 | @end 211 | 212 | @interface NSArray (JSONKitSerializing) 213 | - (NSData *)JSONData; 214 | - (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error; 215 | - (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error; 216 | - (NSString *)JSONString; 217 | - (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error; 218 | - (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error; 219 | @end 220 | 221 | @interface NSDictionary (JSONKitSerializing) 222 | - (NSData *)JSONData; 223 | - (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error; 224 | - (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error; 225 | - (NSString *)JSONString; 226 | - (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error; 227 | - (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error; 228 | @end 229 | 230 | #ifdef __BLOCKS__ 231 | 232 | @interface NSArray (JSONKitSerializingBlockAdditions) 233 | - (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error; 234 | - (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error; 235 | @end 236 | 237 | @interface NSDictionary (JSONKitSerializingBlockAdditions) 238 | - (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error; 239 | - (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error; 240 | @end 241 | 242 | #endif 243 | 244 | 245 | #endif // __OBJC__ 246 | 247 | #endif // _JSONKIT_H_ 248 | 249 | #ifdef __cplusplus 250 | } // extern "C" 251 | #endif 252 | -------------------------------------------------------------------------------- /HLDeferred/Tests/HLDeferredTest.m: -------------------------------------------------------------------------------- 1 | // 2 | // HLDeferredTest.m 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLDeferred.h" 10 | 11 | @interface HLDeferredTest : GHTestCase 12 | @end 13 | 14 | @interface HLDeferredTestCanceller : NSObject 15 | { 16 | BOOL success; 17 | } 18 | 19 | - (BOOL) succeeded; 20 | 21 | @end 22 | 23 | @implementation HLDeferredTest 24 | 25 | - (void) testAllocInitDealloc 26 | { 27 | HLDeferred *d = [[HLDeferred alloc] init]; 28 | GHAssertNotNULL(d, nil); 29 | [d release]; 30 | } 31 | 32 | - (void) testOneCallback 33 | { 34 | HLDeferred *d = [[HLDeferred alloc] init]; 35 | __block BOOL success = NO; 36 | __block id blockResult = nil; 37 | 38 | [d then: ^(id result) { 39 | success = YES; 40 | blockResult = [result retain]; 41 | return result; 42 | }]; 43 | 44 | [d takeResult: @"success"]; 45 | GHAssertTrue(success, @"callback did not run"); 46 | GHAssertEqualStrings(blockResult, @"success", @"unexpected callback result"); 47 | [blockResult release]; 48 | [d release]; 49 | } 50 | 51 | - (void) testMultipleCallbacks 52 | { 53 | HLDeferred *d = [[HLDeferred alloc] init]; 54 | __block int callbackCount = 0; 55 | int count = 0; 56 | [d then: ^(id result) { 57 | callbackCount++; 58 | GHAssertEqualStrings(result, @"starting", @"unexpected callback result"); 59 | return @"first"; 60 | }]; 61 | count++; 62 | 63 | [d then: ^(id result) { 64 | callbackCount++; 65 | GHAssertEqualStrings(result, @"first", @"unexpected callback result"); 66 | return @"second"; 67 | }]; 68 | count++; 69 | 70 | [d then: ^(id result) { 71 | callbackCount++; 72 | GHAssertEqualStrings(result, @"second", @"unexpected callback result"); 73 | return @"blah"; 74 | }]; 75 | count++; 76 | 77 | [d takeResult: @"starting"]; 78 | GHAssertEquals(count, callbackCount, @"count doesn't equal callbackCount"); 79 | 80 | __block HLFailure *failed = nil; 81 | [d fail: ^id(HLFailure *failure) { 82 | failed = [failure retain]; 83 | return failure; 84 | }]; 85 | GHAssertNil([failed autorelease], @"%@", [failed value]); 86 | 87 | [d release]; 88 | } 89 | 90 | - (void) testOneErrback 91 | { 92 | HLDeferred *d = [[HLDeferred alloc] init]; 93 | __block BOOL success = NO; 94 | __block NSException *blockException = nil; 95 | 96 | [d fail: ^(HLFailure *failure) { 97 | @try { 98 | success = YES; 99 | GHAssertEqualStrings([failure value], @"success", @"unexpected errback result"); 100 | } @catch (NSException *exception) { 101 | blockException = [exception retain]; 102 | } @finally { 103 | return failure; 104 | } 105 | }]; 106 | 107 | [d takeError: @"success"]; 108 | GHAssertTrue(success, @"errback did not run"); 109 | GHAssertNil([blockException autorelease], @"%@", blockException); 110 | 111 | [d release]; 112 | } 113 | 114 | - (void) testMultipleErrbacks 115 | { 116 | HLDeferred *d = [[HLDeferred alloc] init]; 117 | __block int errbackCount = 0; 118 | int count = 0; 119 | [d fail: ^(HLFailure *failure) { 120 | errbackCount++; 121 | GHAssertEqualStrings([failure value], @"starting", @"unexpected callback result"); 122 | return failure; 123 | }]; 124 | count++; 125 | 126 | [d fail: ^(HLFailure *failure) { 127 | errbackCount++; 128 | GHAssertEqualStrings([failure value], @"starting", @"unexpected callback result"); 129 | return failure; 130 | }]; 131 | count++; 132 | 133 | [d fail: ^(HLFailure *failure) { 134 | errbackCount++; 135 | GHAssertEqualStrings([failure value], @"starting", @"unexpected callback result"); 136 | return failure; 137 | }]; 138 | count++; 139 | 140 | [d takeError: @"starting"]; 141 | GHAssertEquals(count, errbackCount, @"count doesn't equal errbackCount"); 142 | 143 | __block id blockResult = nil; 144 | [d then: ^id(id result) { 145 | blockResult = [result retain]; 146 | return result; 147 | }]; 148 | GHAssertNil([blockResult autorelease], @"%@", blockResult); 149 | 150 | [d release]; 151 | } 152 | 153 | - (void) testSwitchingBetweenCallbacksAndErrbacks 154 | { 155 | HLDeferred *d = [[HLDeferred alloc] init]; 156 | [d then: ^(id result) { 157 | return [HLFailure wrap: @"ok"]; 158 | } fail: ^(HLFailure *failure) { 159 | GHFail(@"errback should not have been called"); 160 | return failure; 161 | }]; 162 | 163 | [d then: ^(id result) { 164 | GHFail(@"callback should not have been called"); 165 | return result; 166 | } fail: ^(HLFailure *failure) { 167 | GHAssertEqualStrings(@"ok", [failure value], @"expected ok from previous callback"); 168 | return @"ok"; 169 | }]; 170 | 171 | [d then: ^(id result) { 172 | GHAssertEqualStrings(@"ok", result, @"expected ok from previous errback"); 173 | return result; 174 | } fail: ^(HLFailure *failure) { 175 | GHFail(@"errback should not have been called"); 176 | return failure; 177 | }]; 178 | 179 | __block HLFailure *failed = nil; 180 | [d fail: ^id(HLFailure *failure) { 181 | failed = [failure retain]; 182 | return failure; 183 | }]; 184 | GHAssertNil([failed autorelease], @"%@", [failed value]); 185 | 186 | [d release]; 187 | } 188 | 189 | - (void) testRaisingExceptionsInCallbacks 190 | { 191 | HLDeferred *d = [[HLDeferred alloc] init]; 192 | 193 | __block BOOL success = NO; 194 | 195 | [d then: ^id(id result) { 196 | [NSException raise: @"TestException" format: @""]; 197 | return result; 198 | }]; 199 | 200 | [d fail: ^id(HLFailure *failure) { 201 | success = YES; 202 | return failure; 203 | }]; 204 | 205 | [d takeResult: @"starting"]; 206 | 207 | GHAssertTrue(success, @"errback should have bene called"); 208 | 209 | __block id blockResult = nil; 210 | [d then: ^id(id result) { 211 | blockResult = [result retain]; 212 | return result; 213 | }]; 214 | GHAssertNil([blockResult autorelease], @"%@", blockResult); 215 | 216 | [d release]; 217 | } 218 | 219 | - (void) testPausing 220 | { 221 | HLDeferred *d1 = [[HLDeferred alloc] init]; 222 | HLDeferred *d2 = [[HLDeferred alloc] init]; 223 | 224 | __block int x = 0; 225 | 226 | [d1 then: ^id(id result) { 227 | GHTestLog(@"x=%d: d1 then (first) %@", x, result); 228 | GHAssertEquals(0, x, nil); 229 | x++; 230 | return d2; 231 | }]; 232 | 233 | [d2 then: ^id(id result) { 234 | GHTestLog(@"x=%d: d2 then (first) %@", x, result); 235 | GHAssertEquals(1, x, nil); 236 | x++; 237 | return @"ok"; 238 | }]; 239 | 240 | [d2 then: ^id(id result) { 241 | GHTestLog(@"x=%d: d2 then (second) %@", x, result); 242 | GHAssertEquals(2, x, nil); 243 | GHAssertEqualStrings(@"ok", result, nil); 244 | x++; 245 | return @"d2-second"; 246 | }]; 247 | 248 | // this should not run until d2 receives takeResult: 249 | [d1 then: ^id(id result) { 250 | GHTestLog(@"x=%d: d1 then (second) %@", x, result); 251 | GHAssertEquals(3, x, nil); 252 | GHAssertEqualStrings(@"d2-second", result, nil); 253 | x++; 254 | return @"d1-second"; 255 | }]; 256 | 257 | GHAssertEquals(x, 0, nil); 258 | [d1 takeResult: @"starting"]; 259 | [d2 takeResult: @"starting"]; 260 | 261 | [d1 then: ^id(id result) { 262 | GHTestLog(@"x=%d: d1 then (third) %@", x, result); 263 | GHAssertEquals(4, x, nil); 264 | GHAssertEqualStrings(@"d1-second", result, nil); 265 | x++; 266 | return @"d1-third"; 267 | }]; 268 | 269 | [d2 then: ^id(id result) { 270 | GHTestLog(@"x=%d: d2 then (third) %@", x, result); 271 | GHAssertEquals(5, x, nil); 272 | GHAssertEqualStrings(@"d2-second", result, nil); 273 | x++; 274 | return @"d2-third"; 275 | }]; 276 | 277 | __block HLFailure *failed = nil; 278 | [d1 fail: ^(HLFailure *failure) { 279 | failed = [failure retain]; 280 | return failure; 281 | }]; 282 | GHAssertNil([failed autorelease], @"%@", [failed value]); 283 | failed = nil; 284 | 285 | [d2 fail: ^(HLFailure *failure) { 286 | failed = [failure retain]; 287 | return failure; 288 | }]; 289 | GHAssertNil([failed autorelease], @"%@", [failed value]); 290 | failed = nil; 291 | 292 | [d1 release]; 293 | [d2 release]; 294 | } 295 | 296 | - (void) testNotifying 297 | { 298 | HLDeferred *d1 = [[HLDeferred alloc] init]; 299 | HLDeferred *d2 = [[HLDeferred alloc] init]; 300 | 301 | [d1 then: ^(id result) { 302 | GHAssertEqualStrings(@"starting", result, nil); 303 | return @"d1-result"; 304 | }]; 305 | 306 | [d1 notify: d2]; 307 | 308 | [d2 then: ^(id result) { 309 | GHAssertEqualStrings(@"d1-result", result, nil); 310 | return @"d2-result-after-d1-notified-d2"; 311 | }]; 312 | 313 | [d1 then: ^(id result) { 314 | GHAssertEqualStrings(@"d1-result", result, nil); 315 | return result; 316 | }]; 317 | 318 | [d2 then: ^(id result) { 319 | GHAssertEqualStrings(@"d2-result-after-d1-notified-d2", result, nil); 320 | return result; 321 | }]; 322 | 323 | [d1 takeResult: @"starting"]; 324 | 325 | HLDeferred *d3 = [HLDeferred deferredObserving: d2]; 326 | GHAssertNotNil(d3, nil); 327 | 328 | [d3 then:^ (id result) { 329 | GHAssertEqualStrings(@"d2-result-after-d1-notified-d2", result, nil); 330 | return result; 331 | }]; 332 | 333 | __block HLFailure *failed = nil; 334 | [d1 fail: ^id(HLFailure *failure) { 335 | failed = [failure retain]; 336 | return failure; 337 | }]; 338 | GHAssertNil([failed autorelease], @"%@", [failed value]); 339 | failed = nil; 340 | 341 | [d2 fail: ^id(HLFailure *failure) { 342 | failed = [failure retain]; 343 | return failure; 344 | }]; 345 | GHAssertNil([failed autorelease], @"%@", [failed value]); 346 | failed = nil; 347 | 348 | [d3 fail: ^id(HLFailure *failure) { 349 | failed = [failure retain]; 350 | return failure; 351 | }]; 352 | GHAssertNil([failed autorelease], @"%@", [failed value]); 353 | 354 | [d1 release]; 355 | [d2 release]; 356 | } 357 | 358 | - (void) testCancel 359 | { 360 | HLDeferredTestCanceller *c = [[HLDeferredTestCanceller alloc] init]; 361 | HLDeferred *d = [[HLDeferred alloc] initWithCanceller: c]; 362 | GHAssertEquals(c, [d canceller], @"deferred didn't remember canceller"); 363 | GHAssertFalse([c succeeded], @"canceller was called prematurely"); 364 | 365 | __block BOOL success = NO; 366 | __block HLFailure *theFailure = nil; 367 | 368 | [d fail: ^(HLFailure *failure) { 369 | success = YES; 370 | theFailure = [failure retain]; 371 | return failure; 372 | }]; 373 | 374 | GHAssertFalse(success, @"errback run too soon"); 375 | [d cancel]; 376 | 377 | GHAssertTrue(success, @"errback should have run"); 378 | GHAssertEquals([[theFailure autorelease] value], kHLDeferredCancelled, @"errback should have been run with a kHLDeferredCancelled value"); 379 | 380 | GHAssertTrue([c succeeded], @"canceller was not called"); 381 | [d release]; 382 | [c release]; 383 | } 384 | 385 | - (void) testFinalizerNoCallbacks 386 | { 387 | HLDeferred *d = [[HLDeferred alloc] init]; 388 | __block BOOL success = NO; 389 | __block NSException *blockException = nil; 390 | 391 | [d thenFinally: ^(id result) { 392 | @try { 393 | success = YES; 394 | GHAssertEqualStrings(result, @"success", @"unexpected callback result"); 395 | } @catch (NSException *exception) { 396 | blockException = [exception retain]; 397 | } @finally { 398 | return result; 399 | } 400 | }]; 401 | 402 | [d takeResult: @"success"]; 403 | GHAssertTrue(success, @"callback did not run"); 404 | GHAssertNil([blockException autorelease], @"%@", blockException); 405 | [d release]; 406 | } 407 | 408 | - (void) testFinalizerOneCallback 409 | { 410 | HLDeferred *d = [[HLDeferred alloc] init]; 411 | NSMutableString *s = [[NSMutableString alloc] init]; 412 | __block NSException *blockException = nil; 413 | 414 | [d thenFinally: ^(id result) { 415 | @try { 416 | GHAssertEqualStrings(result, @"success", @"unexpected callback result"); 417 | } @catch (NSException *exception) { 418 | blockException = [exception retain]; 419 | } @finally { 420 | [s appendString: @"f"]; 421 | return result; 422 | } 423 | }]; 424 | [d then: ^(id result) { 425 | GHAssertEqualStrings(result, @"success", @"unexpected callback result"); 426 | [s appendString: @"c"]; 427 | return result; 428 | }]; 429 | 430 | __block HLFailure *failed = nil; 431 | [d fail: ^(HLFailure *failure) { 432 | failed = [failure retain]; 433 | return failure; 434 | }]; 435 | 436 | [d takeResult: @"success"]; 437 | GHAssertNil([blockException autorelease], @"%@", blockException); 438 | GHAssertTrue([s length] > 0, @"callback did not run"); 439 | GHAssertEqualStrings(s, @"cf", @"callback should have run, then finalizer"); 440 | GHAssertNil([failed autorelease], @"%@", [failed value]); 441 | [s release]; 442 | [d release]; 443 | } 444 | 445 | - (void) testTwoFinalizersThrows 446 | { 447 | HLDeferred *d = [[HLDeferred alloc] init]; 448 | 449 | [d thenFinally: ^(id result) { 450 | return result; 451 | }]; 452 | 453 | void (^shouldThrow)(void) = ^{ 454 | [d thenFinally: ^(id _) { return _; }]; 455 | }; 456 | 457 | GHAssertThrows(shouldThrow(), @"should have thrown as there was already a finalizer"); 458 | 459 | [d takeResult: @""]; 460 | [d release]; 461 | } 462 | 463 | - (void) testFinalizerAfterRunThrows 464 | { 465 | HLDeferred *d = [[HLDeferred alloc] init]; 466 | 467 | [d thenFinally: ^(id result) { 468 | return result; 469 | }]; 470 | 471 | [d takeResult: @""]; 472 | 473 | void (^shouldThrow)(void) = ^{ 474 | [d thenFinally: ^(id _) { return _; }]; 475 | }; 476 | 477 | GHAssertThrows(shouldThrow(), @"should have thrown as the Deferred already ran"); 478 | 479 | [d release]; 480 | } 481 | 482 | @end 483 | 484 | @implementation HLDeferredTestCanceller 485 | 486 | - (id) init 487 | { 488 | self = [super init]; 489 | if (self) { 490 | success = NO; 491 | } 492 | return self; 493 | } 494 | 495 | - (void) deferredWillCancel: (HLDeferred *)d 496 | { 497 | success = YES; 498 | [d takeError: kHLDeferredCancelled]; 499 | } 500 | 501 | - (BOOL) succeeded 502 | { 503 | return success; 504 | } 505 | 506 | @end 507 | -------------------------------------------------------------------------------- /HLDeferred/Tests/HLDeferredListTest.m: -------------------------------------------------------------------------------- 1 | // 2 | // HLDeferredListTest.m 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLDeferredList.h" 10 | 11 | @interface HLDeferredListTest : GHTestCase 12 | @end 13 | 14 | @interface HLDeferredListTestCanceller : NSObject 15 | { 16 | BOOL success; 17 | } 18 | 19 | - (BOOL) succeeded; 20 | 21 | @end 22 | 23 | @implementation HLDeferredListTest 24 | 25 | - (void) testAllocInitDealloc 26 | { 27 | HLDeferredList *d = [[HLDeferredList alloc] initWithDeferreds: [NSArray array]]; 28 | GHAssertNotNULL(d, nil); 29 | [d release]; 30 | } 31 | 32 | - (void) testFireOnFirstResultEmptyList 33 | { 34 | HLDeferredList *d = [[HLDeferredList alloc] initWithDeferreds: [NSArray array] 35 | fireOnFirstResult: YES]; 36 | GHAssertFalse([d isCalled], @"empty HLDeferredList shouldn't immediately resolve if fireOnFirstResult is YES"); 37 | [d release]; 38 | } 39 | 40 | - (void) testFireOnFirstResultOnCreation 41 | { 42 | HLDeferred *d1 = [HLDeferred deferredWithResult: @"ok"]; 43 | HLDeferred *d2 = [[HLDeferred alloc] init]; 44 | 45 | HLDeferredList *d = [[HLDeferredList alloc] initWithDeferreds: [NSArray arrayWithObjects: d1, d2, nil] 46 | fireOnFirstResult: YES]; 47 | GHAssertTrue([d isCalled], @"HLDeferredList with results should immediately resolve if fireOnFirstResult is YES"); 48 | [d release]; 49 | // d1 is autoreleased 50 | [d2 release]; 51 | } 52 | 53 | - (void) testFireOnFirstResultAfterCreation 54 | { 55 | HLDeferred *d1 = [[HLDeferred alloc] init]; 56 | HLDeferred *d2 = [[HLDeferred alloc] init]; 57 | 58 | HLDeferredList *d = [[HLDeferredList alloc] initWithDeferreds: [NSArray arrayWithObjects: d1, d2, nil] 59 | fireOnFirstResult: YES]; 60 | GHAssertFalse([d isCalled], @"HLDeferredList shouldn't immediately resolve, no results yet"); 61 | [d1 takeResult: @"ok"]; 62 | GHAssertTrue([d isCalled], @"HLDeferredList should resolve with 1 result if fireOnFirstResult is YES"); 63 | 64 | __block BOOL success = NO; 65 | __block NSException *blockException = nil; 66 | 67 | [d1 then: ^(id result) { 68 | @try { 69 | success = YES; 70 | GHAssertEqualStrings(result, @"ok", @"first result not received"); 71 | } @catch (NSException *exception) { 72 | blockException = [exception retain]; 73 | } @finally { 74 | return result; 75 | } 76 | }]; 77 | 78 | GHAssertTrue(success, @"callback wasn't called on resolved HLDeferredList"); 79 | GHAssertNil([blockException autorelease], @"%@", blockException); 80 | 81 | [d release]; 82 | [d1 release]; 83 | [d2 release]; 84 | } 85 | 86 | - (void) testEmptyList 87 | { 88 | HLDeferredList *d = [[HLDeferredList alloc] initWithDeferreds: [NSArray array]]; 89 | GHAssertTrue([d isCalled], @"empty HLDeferredList didn't immediately resolve"); 90 | [d release]; 91 | } 92 | 93 | - (void) testOneResult 94 | { 95 | HLDeferred *d1 = [[HLDeferred alloc] init]; 96 | 97 | HLDeferredList *d = [[HLDeferredList alloc] initWithDeferreds: [NSArray arrayWithObjects: d1, nil]]; 98 | GHAssertFalse([d isCalled], @"HLDeferredList shouldn't immediately resolve, no results yet"); 99 | [d1 takeResult: @"ok"]; 100 | GHAssertTrue([d isCalled], @"HLDeferredList should be resolved"); 101 | 102 | __block BOOL success = NO; 103 | __block NSException *blockException = nil; 104 | 105 | [d then: ^(id result) { 106 | @try { 107 | success = YES; 108 | GHAssertEqualStrings([result objectAtIndex: 0], @"ok", @"expected result not received"); 109 | } @catch (NSException *exception) { 110 | blockException = [exception retain]; 111 | } @finally { 112 | return result; 113 | } 114 | }]; 115 | 116 | GHAssertTrue(success, @"callback wasn't called on resolved HLDeferredList"); 117 | GHAssertNil([blockException autorelease], @"%@", blockException); 118 | [d release]; 119 | [d1 release]; 120 | } 121 | 122 | - (void) testOneError 123 | { 124 | HLDeferred *d1 = [[HLDeferred alloc] init]; 125 | 126 | HLDeferredList *d = [[HLDeferredList alloc] initWithDeferreds: [NSArray arrayWithObjects: d1, nil]]; 127 | GHAssertFalse([d isCalled], @"HLDeferredList shouldn't immediately resolve, no results yet"); 128 | [d1 takeError: @"ok"]; 129 | GHAssertTrue([d isCalled], @"HLDeferredList should be resolved"); 130 | 131 | __block BOOL success = NO; 132 | __block NSException *blockException = nil; 133 | 134 | [d then: ^(id result) { 135 | @try { 136 | success = YES; 137 | GHAssertEquals((int)[result count], 1, @"expected one result"); 138 | GHAssertTrue([[result objectAtIndex: 0] isKindOfClass: [HLFailure class]], @"first result should be HLFailure"); 139 | GHAssertEqualStrings([(HLFailure *)[result objectAtIndex: 0] value], @"ok", @"expected first result value not received"); 140 | } @catch (NSException *exception) { 141 | blockException = [exception retain]; 142 | } @finally { 143 | return result; 144 | } 145 | }]; 146 | 147 | GHAssertTrue(success, @"callback wasn't called on resolved HLDeferredList"); 148 | GHAssertNil([blockException autorelease], @"%@", blockException); 149 | 150 | [d release]; 151 | [d1 release]; 152 | } 153 | 154 | - (void) testOneResultCallbackBeforeResolution 155 | { 156 | HLDeferred *d1 = [[HLDeferred alloc] init]; 157 | 158 | HLDeferredList *d = [[HLDeferredList alloc] initWithDeferreds: [NSArray arrayWithObjects: d1, nil]]; 159 | GHAssertFalse([d isCalled], @"HLDeferredList shouldn't immediately resolve, no results yet"); 160 | 161 | __block BOOL success = NO; 162 | __block NSException *blockException = nil; 163 | 164 | [d then: ^(id result) { 165 | @try { 166 | success = YES; 167 | GHAssertEqualStrings([result objectAtIndex: 0], @"ok", @"expected result not received"); 168 | } @catch (NSException *exception) { 169 | blockException = [exception retain]; 170 | } @finally { 171 | return result; 172 | } 173 | }]; 174 | 175 | [d1 takeResult: @"ok"]; 176 | GHAssertTrue([d isCalled], @"HLDeferredList should be resolved"); 177 | 178 | GHAssertTrue(success, @"callback wasn't called on resolved HLDeferredList"); 179 | GHAssertNil([blockException autorelease], @"%@", blockException); 180 | 181 | [d release]; 182 | [d1 release]; 183 | } 184 | 185 | - (void) testTwoResults 186 | { 187 | HLDeferred *d1 = [[HLDeferred alloc] init]; 188 | HLDeferred *d2 = [[HLDeferred alloc] init]; 189 | 190 | HLDeferredList *d = [[HLDeferredList alloc] initWithDeferreds: [NSArray arrayWithObjects: d1, d2, nil]]; 191 | GHAssertFalse([d isCalled], @"HLDeferredList shouldn't immediately resolve, no results yet"); 192 | [d1 takeResult: @"ok1"]; 193 | GHAssertFalse([d isCalled], @"HLDeferredList shouldn't immediately resolve, results incomplete"); 194 | [d2 takeResult: @"ok2"]; 195 | GHAssertTrue([d isCalled], @"HLDeferredList should be resolved"); 196 | 197 | __block BOOL success = NO; 198 | __block NSException *blockException = nil; 199 | 200 | [d then: ^(id result) { 201 | @try { 202 | success = YES; 203 | GHAssertTrue([result isKindOfClass: [NSArray class]], @"callback result should be NSArray"); 204 | GHAssertEquals((int)[result count], 2, @"expected two results"); 205 | GHAssertEqualStrings([result objectAtIndex: 0], @"ok1", @"expected first result not received"); 206 | GHAssertEqualStrings([result objectAtIndex: 1], @"ok2", @"expected second result not received"); 207 | } @catch (NSException *exception) { 208 | blockException = [exception retain]; 209 | } @finally { 210 | return result; 211 | } 212 | }]; 213 | 214 | GHAssertTrue(success, @"callback wasn't called on resolved HLDeferredList"); 215 | GHAssertNil([blockException autorelease], @"%@", blockException); 216 | 217 | [d release]; 218 | [d1 release]; 219 | [d2 release]; 220 | } 221 | 222 | - (void) testFireOnFirstErrorEmptyList 223 | { 224 | HLDeferredList *d = [[HLDeferredList alloc] initWithDeferreds: [NSArray array] 225 | fireOnFirstError: YES]; 226 | GHAssertTrue([d isCalled], @"empty HLDeferredList should immediately resolve, even when fireOnFirstError is YES"); 227 | [d release]; 228 | } 229 | 230 | - (void) testFireOnFirstErrorOnCreation 231 | { 232 | HLDeferred *d1 = [HLDeferred deferredWithError: @"ok"]; 233 | HLDeferred *d2 = [[HLDeferred alloc] init]; 234 | 235 | HLDeferredList *d = [[HLDeferredList alloc] initWithDeferreds: [NSArray arrayWithObjects: d1, d2, nil] 236 | fireOnFirstError: YES]; 237 | GHAssertTrue([d isCalled], @"HLDeferredList with errors should immediately resolve if fireOnFirstError is YES"); 238 | [d release]; 239 | // d1 is autoreleased 240 | [d2 release]; 241 | } 242 | 243 | - (void) testFireOnFirstErrorAfterCreation 244 | { 245 | HLDeferred *d1 = [[HLDeferred alloc] init]; 246 | HLDeferred *d2 = [[HLDeferred alloc] init]; 247 | 248 | HLDeferredList *d = [[HLDeferredList alloc] initWithDeferreds: [NSArray arrayWithObjects: d1, d2, nil] 249 | fireOnFirstError: YES]; 250 | GHAssertFalse([d isCalled], @"HLDeferredList shouldn't immediately resolve, no results yet"); 251 | [d1 takeError: @"ok"]; 252 | GHAssertTrue([d isCalled], @"HLDeferredList should resolve with 1 error if fireOnFirstError is YES"); 253 | 254 | __block BOOL success = NO; 255 | __block NSException *blockException = nil; 256 | 257 | [d1 fail: ^(HLFailure *failure) { 258 | @try { 259 | success = YES; 260 | GHAssertEqualStrings([failure value], @"ok", @"error not received"); 261 | } @catch (NSException *exception) { 262 | blockException = [exception retain]; 263 | } @finally { 264 | return failure; 265 | } 266 | }]; 267 | 268 | GHAssertTrue(success, @"errback wasn't called on resolved HLDeferred"); 269 | GHAssertNil([blockException autorelease], @"%@", blockException); 270 | blockException = nil; 271 | 272 | success = NO; 273 | 274 | [d fail: ^(HLFailure *failure) { 275 | @try { 276 | success = YES; 277 | GHAssertEqualStrings([failure value], @"ok", @"first error not received"); 278 | } @catch (NSException *exception) { 279 | blockException = [exception retain]; 280 | } @finally { 281 | return failure; 282 | } 283 | }]; 284 | 285 | GHAssertTrue(success, @"errback wasn't called on resolved HLDeferredList"); 286 | GHAssertNil([blockException autorelease], @"%@", blockException); 287 | 288 | [d release]; 289 | [d1 release]; 290 | [d2 release]; 291 | } 292 | 293 | - (void) testConsumeErrors 294 | { 295 | HLDeferred *d1 = [[HLDeferred alloc] init]; 296 | 297 | HLDeferredList *d = [[HLDeferredList alloc] initWithDeferreds: [NSArray arrayWithObjects: d1, nil] 298 | consumeErrors: YES]; 299 | 300 | __block NSException *blockException = nil; 301 | 302 | [d1 then: ^(id result) { 303 | @try { 304 | GHAssertNil(result, @"callback result should be nil (consumed by HLDeferredList)"); 305 | } @catch (NSException *exception) { 306 | blockException = [exception retain]; 307 | } @finally { 308 | return result; 309 | } 310 | } fail: ^(HLFailure *failure) { 311 | @try { 312 | GHFail(@"errback was called but the error should have been consumed by the HLDeferredList"); 313 | } @catch (NSException *exception) { 314 | blockException = [exception retain]; 315 | } @finally { 316 | return failure; 317 | } 318 | }]; 319 | 320 | GHAssertFalse([d isCalled], @"HLDeferredList shouldn't immediately resolve, no results yet"); 321 | [d1 takeError: @"ok"]; 322 | GHAssertTrue([d1 isCalled], @"Deferred with error should resolve"); 323 | GHAssertTrue([d isCalled], @"HLDeferredList should resolve with 1 error if fireOnFirstError is YES"); 324 | GHAssertNil([blockException autorelease], @"%@", blockException); 325 | blockException = nil; 326 | 327 | [d then: ^(id result) { 328 | @try { 329 | GHAssertTrue([result isKindOfClass: [NSArray class]], @"callback result should be NSArray"); 330 | GHAssertEquals((int)[result count], 1, @"expected one result"); 331 | GHAssertTrue([[result objectAtIndex: 0] isKindOfClass: [HLFailure class]], @"callback result first element should be HLFailure"); 332 | GHAssertEqualStrings([(HLFailure *)[result objectAtIndex: 0] value], @"ok", @"expected error not received"); 333 | } @catch (NSException *exception) { 334 | blockException = [exception retain]; 335 | } @finally { 336 | return result; 337 | } 338 | }]; 339 | GHAssertNil([blockException autorelease], @"%@", blockException); 340 | 341 | [d release]; 342 | [d1 release]; 343 | } 344 | 345 | - (void) testCancel 346 | { 347 | HLDeferred *d1 = [[HLDeferred alloc] init]; 348 | HLDeferred *d2 = [[HLDeferred alloc] init]; 349 | HLDeferredList *d = [[HLDeferredList alloc] initWithDeferreds: [NSArray arrayWithObjects: d1, d2, nil]]; 350 | __block BOOL success = NO; 351 | __block NSException *blockException = nil; 352 | 353 | [d fail: ^(HLFailure *failure) { 354 | @try { 355 | success = YES; 356 | GHAssertEquals([failure value], kHLDeferredCancelled, @"errback should have been run with a kHLDeferredCancelled value"); 357 | } @catch (NSException *exception) { 358 | blockException = [exception retain]; 359 | } @finally { 360 | return failure; 361 | } 362 | }]; 363 | 364 | GHAssertFalse(success, @"errback run too soon"); 365 | [d cancel]; 366 | GHAssertTrue(success, @"errback should have run"); 367 | GHAssertNil([blockException autorelease], @"%@", blockException); 368 | 369 | [d release]; 370 | [d2 release]; 371 | [d1 release]; 372 | } 373 | 374 | - (void) testCancelDeferredsWhenCancelled 375 | { 376 | HLDeferredListTestCanceller *c1 = [[HLDeferredListTestCanceller alloc] init]; 377 | HLDeferredListTestCanceller *c2 = [[HLDeferredListTestCanceller alloc] init]; 378 | HLDeferred *d1 = [[HLDeferred alloc] initWithCanceller: c1]; 379 | HLDeferred *d2 = [[HLDeferred alloc] initWithCanceller: c2]; 380 | NSArray *list = [[NSArray alloc] initWithObjects: d1, d2, nil]; 381 | HLDeferredList *d = [[HLDeferredList alloc] initWithDeferreds: list]; 382 | [d cancelDeferredsWhenCancelled]; 383 | GHAssertFalse([c1 succeeded], @"canceller 1 was called prematurely"); 384 | GHAssertFalse([c2 succeeded], @"canceller 2 was called prematurely"); 385 | 386 | __block BOOL success = NO; 387 | __block HLFailure *theFailure = nil; 388 | 389 | [d fail: ^(HLFailure *failure) { 390 | theFailure = [failure retain]; 391 | success = YES; 392 | return failure; 393 | }]; 394 | 395 | GHAssertFalse(success, @"errback run too soon"); 396 | [d cancel]; 397 | GHAssertTrue(success, @"errback should have run"); 398 | GHAssertEquals([[theFailure autorelease] value], kHLDeferredCancelled, @"errback should have been run with a kHLDeferredCancelled value"); 399 | 400 | GHAssertTrue([c1 succeeded], @"canceller 1 was not called"); 401 | GHAssertTrue([c2 succeeded], @"canceller 2 was not called"); 402 | [d release]; 403 | [d2 release]; 404 | [d1 release]; 405 | [c2 release]; 406 | [c1 release]; 407 | [list release]; 408 | } 409 | 410 | @end 411 | 412 | @implementation HLDeferredListTestCanceller 413 | 414 | - (id) init 415 | { 416 | self = [super init]; 417 | if (self) { 418 | success = NO; 419 | } 420 | return self; 421 | } 422 | 423 | - (void) deferredWillCancel: (HLDeferred *)d 424 | { 425 | success = YES; 426 | [d takeError: kHLDeferredCancelled]; 427 | } 428 | 429 | - (BOOL) succeeded 430 | { 431 | return success; 432 | } 433 | 434 | @end 435 | -------------------------------------------------------------------------------- /HLDeferred/Classes/HLDeferred.m: -------------------------------------------------------------------------------- 1 | // 2 | // HLDeferred.m 3 | // HLDeferred 4 | // 5 | // Copyright 2011 HeavyLifters Network Ltd.. All rights reserved. 6 | // See included LICENSE file (MIT) for licensing information. 7 | // 8 | 9 | #import "HLDeferred.h" 10 | 11 | NSString * const kHLDeferredCancelled = @"__HLDeferredCancelled__"; 12 | NSString * const kHLDeferredNoResult = @"__HLDeferredNoResult__"; 13 | NSString * const HLDeferredAlreadyCalledException = @"HLDeferredAlreadyCalledException"; 14 | NSString * const HLDeferredAlreadyFinalizedException = @"HLDeferredAlreadyFinalizedException"; 15 | 16 | @interface HLLink : NSObject 17 | { 18 | ThenBlock _thenBlock; 19 | FailBlock _failBlock; 20 | id _result; 21 | } 22 | 23 | @property (nonatomic, copy) ThenBlock thenBlock; 24 | @property (nonatomic, copy) FailBlock failBlock; 25 | @property (nonatomic, retain) id result; 26 | 27 | - (id) initWithThenBlock: (ThenBlock)cb_ failBlock: (FailBlock)fb_; 28 | 29 | - (id) process: (id)input; 30 | 31 | @end 32 | 33 | @implementation HLLink 34 | 35 | @synthesize thenBlock=_thenBlock; 36 | @synthesize failBlock=_failBlock; 37 | @synthesize result=_result; 38 | 39 | - (id) initWithThenBlock: (ThenBlock)thenBlock_ failBlock: (FailBlock)failBlock_ 40 | { 41 | self = [super init]; 42 | if (self) { 43 | _thenBlock = [thenBlock_ copy]; 44 | _failBlock = [failBlock_ copy]; 45 | } 46 | return self; 47 | } 48 | 49 | - (void) dealloc 50 | { 51 | [_thenBlock release]; _thenBlock = nil; 52 | [_failBlock release]; _failBlock = nil; 53 | [super dealloc]; 54 | } 55 | 56 | - (id) process: (id)input 57 | { 58 | id result = input; 59 | if ([input isKindOfClass: [HLFailure class]]) { 60 | FailBlock fb = [self failBlock]; 61 | if (fb) { 62 | result = fb((HLFailure *)input); 63 | } 64 | } else { 65 | ThenBlock tb = [self thenBlock]; 66 | if (tb) { 67 | result = tb(input); 68 | } 69 | } 70 | return result; 71 | } 72 | 73 | @end 74 | 75 | @interface HLContinuationLink : HLLink 76 | { 77 | HLDeferred *deferred_; 78 | } 79 | 80 | @property (nonatomic, readonly, retain) HLDeferred *deferred; 81 | 82 | - (id) initWithDeferred: (HLDeferred *)d; 83 | 84 | @end 85 | 86 | @implementation HLContinuationLink 87 | 88 | @synthesize deferred=deferred_; 89 | 90 | - (id) initWithDeferred: (HLDeferred *)deferred 91 | { 92 | self = [super initWithThenBlock: nil failBlock: nil]; 93 | if (self) { 94 | deferred_ = [deferred retain]; 95 | } 96 | return self; 97 | } 98 | 99 | - (void) dealloc 100 | { 101 | [deferred_ release]; deferred_ = nil; 102 | [super dealloc]; 103 | } 104 | 105 | - (id) process: (id)input 106 | { 107 | return input; 108 | } 109 | 110 | @end 111 | 112 | @interface HLDeferred () 113 | 114 | @property (nonatomic, readwrite, assign, getter=isCalled) BOOL called; 115 | @property (nonatomic, retain) id result; 116 | @property (nonatomic, retain) HLDeferred *chainedTo; 117 | 118 | - (void) _runCallbacks; 119 | - (void) _startRunCallbacks: (id)aResult; 120 | 121 | - (NSException *) _alreadyCalledException; 122 | - (NSException *) _alreadyChainedException; 123 | - (NSException *) _alreadyFinalizedException; 124 | - (NSException *) _alreadyHasAFinalizerException; 125 | 126 | @end 127 | 128 | @implementation HLDeferred 129 | 130 | @synthesize result=result_; 131 | @synthesize canceller=canceller_; 132 | @synthesize called=called_; 133 | @synthesize chainedTo=chainedTo_; 134 | 135 | + (HLDeferred *) deferredWithResult: (id)aResult { return [[[[self alloc] init] autorelease] takeResult: aResult]; } 136 | + (HLDeferred *) deferredWithError: (id)anError { return [[[[self alloc] init] autorelease] takeError: anError]; } 137 | 138 | + (HLDeferred *) deferredObserving: (HLDeferred *)otherDeferred 139 | { 140 | HLDeferred *result = [[[self alloc] init] autorelease]; 141 | [otherDeferred notify: result]; 142 | return result; 143 | } 144 | 145 | - (id) initWithCanceller: (id ) theCanceller 146 | { 147 | self = [super init]; 148 | if (self) { 149 | called_ = NO; 150 | suppressAlreadyCalled_ = NO; 151 | runningCallbacks_ = NO; 152 | result_ = [kHLDeferredNoResult retain]; 153 | pauseCount_ = 0; 154 | finalized_ = NO; 155 | finalizer_ = nil; 156 | chain_ = [[NSMutableArray alloc] init]; 157 | canceller_ = theCanceller; 158 | } 159 | return self; 160 | } 161 | 162 | - (id) init 163 | { 164 | self = [self initWithCanceller: nil]; 165 | return self; 166 | } 167 | 168 | - (void) dealloc 169 | { 170 | canceller_ = nil; 171 | [result_ release]; result_ = nil; 172 | [finalizer_ release]; finalizer_ = nil; 173 | [chain_ release]; chain_ = nil; 174 | [chainedTo_ release]; chainedTo_ = nil; 175 | [super dealloc]; 176 | } 177 | 178 | - (NSString *)debugDescription 179 | { 180 | NSString *superDescription = [super debugDescription]; 181 | NSString *result = superDescription; 182 | NSString *extra = nil; 183 | if (chainedTo_) { 184 | extra = [NSString stringWithFormat: @" (waiting on %@ at %p)>", 185 | NSStringFromClass([chainedTo_ class]), chainedTo_]; 186 | } else if (result_ == kHLDeferredNoResult) { 187 | extra = @">"; 188 | } else { 189 | extra = [NSString stringWithFormat: @" (result: %@)>", result_]; 190 | } 191 | result = [result stringByReplacingOccurrencesOfString: @">" withString: extra]; 192 | return result; 193 | } 194 | 195 | - (HLDeferred *) thenReturn: (id)aResult { 196 | return [self then: ^(id _) { return aResult; } fail: nil]; 197 | } 198 | 199 | - (HLDeferred *) then: (ThenBlock)cb { return [self then: cb fail: nil ]; } 200 | - (HLDeferred *) fail: (FailBlock)eb { return [self then: nil fail: eb ]; } 201 | - (HLDeferred *) both: (ThenBlock)bb { return [self then: bb fail: bb]; } 202 | 203 | - (HLDeferred *) then: (ThenBlock)cb fail: (FailBlock)eb 204 | { 205 | // NSLog(@"%@ in %@", self, NSStringFromSelector(_cmd)); 206 | if (finalized_) { 207 | @throw [self _alreadyFinalizedException]; 208 | } else { 209 | HLLink *link = [[HLLink alloc] initWithThenBlock: cb failBlock: eb]; 210 | [chain_ addObject: link]; 211 | [link release]; link = nil; 212 | if ([self isCalled]) { 213 | [self _runCallbacks]; 214 | } 215 | } 216 | return self; 217 | } 218 | 219 | - (HLDeferred *) thenFinally: (ThenBlock)aThenFinalizer { return [self thenFinally: aThenFinalizer failFinally: nil ]; } 220 | - (HLDeferred *) failFinally: (FailBlock)aFailFinalizer { return [self thenFinally: nil failFinally: aFailFinalizer]; } 221 | - (HLDeferred *) bothFinally: (ThenBlock)aBothFinalizer { return [self thenFinally: aBothFinalizer failFinally: aBothFinalizer]; } 222 | 223 | - (HLDeferred *) thenFinally: (ThenBlock)aThenFinalizer failFinally: (FailBlock)aFailFinalizer 224 | { 225 | if (finalized_) { 226 | @throw [self _alreadyFinalizedException]; 227 | } else if (finalizer_) { 228 | @throw [self _alreadyHasAFinalizerException]; 229 | } else { 230 | finalizer_ = [[HLLink alloc] initWithThenBlock: aThenFinalizer failBlock: aFailFinalizer]; 231 | if ([self isCalled]) { 232 | [self _runCallbacks]; 233 | } 234 | } 235 | return self; 236 | } 237 | 238 | - (HLDeferred *) takeResult: (id)aResult 239 | { 240 | // NSLog(@"%@ in %@", self, NSStringFromSelector(_cmd)); 241 | [self _startRunCallbacks: aResult]; 242 | return self; 243 | } 244 | 245 | - (HLDeferred *) takeError: (id)anError 246 | { 247 | // NSLog(@"%@ in %@", self, NSStringFromSelector(_cmd)); 248 | id err = anError; 249 | if (![err isKindOfClass: [HLFailure class]]) { 250 | err = [[[HLFailure alloc] initWithValue: anError] autorelease]; 251 | } 252 | [self _startRunCallbacks: err]; 253 | return self; 254 | } 255 | 256 | // this is different than chaining. The result from the other 257 | // HLDeferred's callback chain will not affect this HLDeferred's result. 258 | // this is useful if you cache a HLDeferred and don't want its result 259 | // mutated by its clients. Instead, return a new HLDeferred that is 260 | // notified by the cached HLDeferred. 261 | // Also, check out the convenience method: +deferredObserving: 262 | // 263 | // return [HLDeferred deferredObserving: _cachedDeferred]; 264 | // 265 | - (HLDeferred *) notify: (HLDeferred *)otherDeferred 266 | { 267 | // NSLog(@"%@ in %@", self, NSStringFromSelector(_cmd)); 268 | if (finalized_) { 269 | @throw [self _alreadyFinalizedException]; 270 | } else { 271 | if ([otherDeferred isCalled]) { 272 | @throw [self _alreadyCalledException]; 273 | } else if ([otherDeferred chainedTo]) { 274 | @throw [self _alreadyChainedException]; 275 | } else { 276 | otherDeferred->pauseCount_++; 277 | [otherDeferred setChainedTo: self]; 278 | HLLink *link = [[HLContinuationLink alloc] initWithDeferred: otherDeferred]; 279 | [chain_ addObject: link]; 280 | [link release]; link = nil; 281 | if ([self isCalled]) { 282 | [self _runCallbacks]; 283 | } 284 | } 285 | } 286 | return self; 287 | } 288 | 289 | - (void) cancel 290 | { 291 | if (! [self isCalled]) { 292 | if (canceller_) { 293 | [canceller_ deferredWillCancel: self]; 294 | } else { 295 | suppressAlreadyCalled_ = YES; 296 | } 297 | if ( (! [self isCalled]) && (canceller_ == nil) ) { 298 | // if there is a canceller, the canceller 299 | // must call [d takeError: kHLDeferredCancelled] 300 | [self takeError: kHLDeferredCancelled]; 301 | } 302 | } else if ([result_ isKindOfClass: [HLDeferred class]]) { 303 | [result_ cancel]; 304 | } 305 | } 306 | 307 | #pragma mark - 308 | #pragma mark Private API: Exceptions 309 | 310 | - (NSException *) _alreadyCalledException 311 | { 312 | return [NSException exceptionWithName: HLDeferredAlreadyCalledException 313 | reason: @"this HLDeferred has already been called" 314 | userInfo: [NSDictionary dictionaryWithObject: self 315 | forKey: @"HLDeferred"]]; 316 | } 317 | 318 | - (NSException *) _alreadyFinalizedException 319 | { 320 | return [NSException exceptionWithName: HLDeferredAlreadyFinalizedException 321 | reason: @"this HLDeferred has already been finalized" 322 | userInfo: [NSDictionary dictionaryWithObject: self 323 | forKey: @"HLDeferred"]]; 324 | } 325 | 326 | - (NSException *) _alreadyChainedException 327 | { 328 | return [NSException exceptionWithName: NSInvalidArgumentException 329 | reason: @"this HLDeferred is already chained to another HLDeferred" 330 | userInfo: [NSDictionary dictionaryWithObject: self 331 | forKey: @"HLDeferred"]]; 332 | } 333 | - (NSException *) _alreadyHasAFinalizerException 334 | { 335 | return [NSException exceptionWithName: NSInternalInconsistencyException 336 | reason: @"this HLDeferred already has a finalizer" 337 | userInfo: [NSDictionary dictionaryWithObject: self 338 | forKey: @"HLDeferred"]]; 339 | } 340 | 341 | 342 | #pragma mark - 343 | #pragma mark Private API: processing machinery 344 | 345 | - (void) _startRunCallbacks: (id)aResult 346 | { 347 | // NSLog(@"%@ in %@", self, NSStringFromSelector(_cmd)); 348 | if (finalized_) { 349 | @throw [self _alreadyFinalizedException]; 350 | } 351 | if ([self isCalled]) { 352 | if (suppressAlreadyCalled_) { 353 | suppressAlreadyCalled_ = NO; 354 | return; 355 | } 356 | @throw [self _alreadyCalledException]; 357 | } 358 | [self setCalled: YES]; 359 | [self setResult: aResult]; 360 | [self _runCallbacks]; 361 | } 362 | 363 | - (void) _runCallbacks 364 | { 365 | // NSLog(@"%@ in %@", self, NSStringFromSelector(_cmd)); 366 | if (runningCallbacks_) return; // Don't recursively run callbacks 367 | 368 | // Keep track of all the HLDeferreds encountered while propagating results 369 | // up a chain. The way a HLDeferred gets onto this stack is by having 370 | // added its _continuation() to the callbacks list of a second HLDeferred 371 | // and then that second HLDeferred being fired. ie, if ever had _chainedTo 372 | // set to something other than nil, you might end up on this stack. 373 | NSMutableArray *chain = [NSMutableArray arrayWithObject: self]; 374 | 375 | while ([chain count]) { 376 | HLDeferred *current = [chain lastObject]; 377 | 378 | if (current->pauseCount_) { 379 | // This HLDeferred isn't going to produce a result at all. All the 380 | // HLDeferreds up the chain waiting on it will just have to... 381 | // wait. 382 | return; 383 | } 384 | 385 | BOOL finished = YES; 386 | [current setCalled: YES]; 387 | [current setChainedTo: nil]; 388 | while ([current->chain_ count]) { 389 | HLLink *item = [[current->chain_ objectAtIndex: 0] retain]; 390 | [current->chain_ removeObjectAtIndex: 0]; 391 | 392 | if ([item isKindOfClass: [HLContinuationLink class]]) { 393 | // Give the waiting HLDeferred our current result and then 394 | // forget about that result ourselves. 395 | HLDeferred *chainee = [(HLContinuationLink *)item deferred]; 396 | [chainee setResult: [current result]]; 397 | // [current setResult: nil]; // Twisted does this, HLDeferred does NOT 398 | chainee->pauseCount_--; 399 | [chain addObject: chainee]; 400 | // Delay popping this HLDeferred from the chain 401 | // until after we've dealt with chainee. 402 | finished = NO; 403 | [item release]; item = nil; 404 | break; 405 | } 406 | 407 | @try { 408 | current->runningCallbacks_ = YES; 409 | @try { 410 | [current setResult: [item process: [current result]]]; 411 | } @finally { 412 | current->runningCallbacks_ = NO; 413 | } 414 | if ([[current result] isKindOfClass: [HLDeferred class]]) { 415 | HLDeferred *currentResult = (HLDeferred *)[current result]; 416 | // The result is another HLDeferred. If it has a result, 417 | // we can take it and keep going. 418 | id resultResult = [currentResult result]; 419 | if ((resultResult == kHLDeferredNoResult) || [resultResult isKindOfClass: [HLDeferred class]] || currentResult->pauseCount_) { 420 | // Nope, it didn't. Pause and chain. 421 | current->pauseCount_++; 422 | [current setChainedTo: currentResult]; 423 | // Note: currentResult has no result, so it's not 424 | // running its chain_ right now. Therefore we can 425 | // append to the chain_ list directly instead of 426 | // using then:fail:. 427 | [currentResult->chain_ addObject: [[[HLContinuationLink alloc] initWithDeferred: current] autorelease]]; 428 | break; 429 | } else { 430 | // Yep, it did. Steal it. 431 | [current setResult: resultResult]; 432 | // [currentResult setResult: nil]; // Twisted does this, HLDeferred does NOT 433 | } 434 | } 435 | } @catch (NSException *exception) { 436 | [current setResult: [HLFailure wrap: exception]]; 437 | } @finally { 438 | [item release]; item = nil; 439 | } 440 | } 441 | if (finished) { 442 | if (current->finalizer_ && (current->pauseCount_ == 0)) { 443 | [current->chain_ addObject: current->finalizer_]; 444 | [current->finalizer_ release]; current->finalizer_ = nil; 445 | current->finalized_ = YES; 446 | [current _runCallbacks]; 447 | } 448 | [chain removeLastObject]; 449 | } 450 | } 451 | // NSLog(@"%@ in %@, done", self, NSStringFromSelector(_cmd)); 452 | } 453 | 454 | @end 455 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | HeavyLifters Deferred Library 2 | ============================= 3 | 4 | HLDeferred makes programming asynchronous processes with callbacks easy in Objective-C. Asynchronous data sources are scheduled on an `NSOperationQueue` and provide an [`HLDeferred`][HLD] object that accept callbacks. Callbacks are simple Objective-C blocks. 5 | 6 | An [`HLDeferred`][HLD] object represents a result (or failure) that will become available once its data source retrieves it. This library includes support for creating data sources using concurrent or non-concurrent `NSOperation` objects, but you are not limited to this approach in any way. 7 | 8 | HLDeferred is based on `Deferred` classes from [Twisted Python](http://twistedmatrix.com/). The Twisted pattern has been adapted to many languages and environments. HeavyLifters provides and uses implementations in Objective-C, Objective-J, JavaScript, Node.js, and Java. 9 | 10 | Why should I use this? 11 | ---------------------- 12 | 13 | Your classes are getting bloated and convoluted because of "delegate hell" (`NSURLConnectionDelegate` and friends). You just want to fetch some data, perhaps JSON using HTTP, act on it once it's available, and know if fetching fails. Tracing your code has become a chore because processes are split across many delegate methods, or you have to maintain complicated state machines to get nested asynchronous processes to work correctly. 14 | 15 | You wish there was an easy way do to simple things like this. There is. 16 | 17 | Requirements 18 | ------------ 19 | - Xcode 3.2.5 with iOS 4.2 SDK (or later) 20 | - iOS 4.x devices are supported 21 | 22 | Note: This code would probably work on Mac OS X 10.6+, but it hasn't been tested there. 23 | 24 | Building HLDeferred 25 | ------------------- 26 | - Clone HLDeferred from GitHub: `git clone git://github.com/heavylifters/HLDeferred-objc.git` 27 | - Open HLDeferred-objc/HLDeferred/HLDeferred.xcodeproj in Xcode 28 | - Build 29 | 30 | Using HLDeferred in your iOS app project 31 | ---------------------------------------- 32 | - Drag-and-drop the HLDeferred project icon at the top of HLDeferred's Groups & Files pane into your app project 33 | - In your app target inspector (General tab), make your project dependent on the HLDeferred target in HLDeferred.xcodeproj 34 | - Drag the libHLDeferred.a static library (under HLDeferred.xcodeproj in your app project) inside the "Link Binary with Libraries" section of your app target. 35 | - Drag the "HLDeferred Headers" group from the HLDeferred project into your app project. 36 | - import and use the HLDeferred classes in your app 37 | 38 | Running Unit Tests 39 | ------------------ 40 | - [Download GHUnit for iOS](https://github.com/downloads/gabriel/gh-unit/GHUnitIOS-0.4.28.zip). (or [build it from source](https://github.com/gabriel/gh-unit) if you prefer) 41 | - Copy GHUnitIOS.framework into HLDeferred-objc/HLDeferred/Frameworks. 42 | - Build and run the Tests target in Xcode. 43 | 44 | How it works 45 | ------------ 46 | 47 | You can create an [`HLDeferred`][HLD] object directly, but you typically request one from a data source. You get the data source's result by adding **callbacks** and/or **errbacks** to the **callback chain** of the [`HLDeferred`][HLD] object the data source provides. When the data source has the result (or determines failure), the [`HLDeferred`][HLD] object is sent a `-takeResult:` message (or `-takeError:`). At this point, the [`HLDeferred`][HLD] object's callback chain is **fired**, meaning each link in the chain (a callback or errback) is called in turn. The result is the input to the first callback, and its output is the input to the next callback (and so on). 48 | 49 | If a callback (or errback) returns an exception, the next errback is called, otherwise the next callback is called. 50 | 51 | ![Deferred-process](https://github.com/heavylifters/HLDeferred-objc/raw/master/Documentation/images/twisted/deferred-process.png) 52 | 53 | The Most Basic Example 54 | ---------------------- 55 | 56 | - (void) demonstration 57 | { 58 | HLDeferred *d = [[HLDeferred alloc] init]; 59 | NSLog(@"created HLDeferred object"); 60 | 61 | // add a callback 62 | [d then: ^(id result) { 63 | NSLog(@"Hello, %@", result); 64 | return result; 65 | }]; 66 | NSLog(@"added a callback to the HLDeferred's callback chain"); 67 | 68 | // resolve the HLDeferred, which fires the callback chain 69 | [d takeResult: @"World"]; 70 | NSLog(@"In the console, you should see 'Hello, World' in the line above"); 71 | 72 | // Note: use [d takeError: @"DISASTER!"] to indicate failure 73 | 74 | [d release]; 75 | } 76 | 77 | Adding callbacks and errbacks 78 | ----------------------------- 79 | 80 | Each **link** in a callback chain is a pair of Objective-C blocks, representing a **callback** and an **errback**. Firing the chain executes the callback **OR** errback of **each link, in sequence**. For each link, its callback is executed if its input is a result; the errback is executed if its input is a failure (failures are represented by [`HLFailure`][HLF] objects). 81 | 82 | ### Adding (just) a callback ### 83 | 84 | To append a link with a callback to an [`HLDeferred`][HLD] object, send it the `-then:` message, passing in a `ThenBlock`. Example: 85 | 86 | [aDeferred then: ^(id result) { 87 | // do something useful with the result 88 | return result; 89 | }]; 90 | 91 | [`HLDeferred`][HLD] adds a link to its chain with your callback and a "passthrough" errback. The passthrough errback simply returns its exception parameter. 92 | 93 | ### Adding (just) an errback ### 94 | 95 | To append a link with an errback to an [`HLDeferred`][HLD] object, send it the `-fail:` message, passing in a `FailBlock`. Example: 96 | 97 | [aDeferred fail: ^(HLFailure *failure) { 98 | // optionally do something useful with [failure value] 99 | return failure; 100 | }]; 101 | 102 | [`HLDeferred`][HLD] adds a link to its chain with your errback and a "passthrough" callback. The passthrough callback simply returns its result parameter. 103 | 104 | ### Adding a callback and an errback ### 105 | 106 | To add a link with a callback *and* errback to an [`HLDeferred`][HLD] object, send it either the `-then:fail:` message or the `both:` message. 107 | 108 | Use `-then:fail:` when you want different behaviour in the case of success or failure: 109 | 110 | [aDeferred then: ^(id result) { 111 | // do something useful with the result 112 | return result; 113 | } fail: ^(HLFailure *failure) { 114 | // optionally do something useful with [failure value] 115 | return failure; 116 | }] 117 | 118 | Use `-both:` when you intend to do the same thing in either case: 119 | 120 | [aDeferred both: ^(id result) { 121 | // in the case of failure, result is an HLFailure 122 | // do something in either case 123 | return result; 124 | }] 125 | 126 | HLDeferred in practice 127 | ---------------------- 128 | 129 | By convention, names of methods returning an [`HLDeferred`][HLD] object are prefixed with "request", such as: 130 | 131 | // result is a MyThing object 132 | - (HLDeferred *) requestDistantInformation; 133 | 134 | It might be nice if Objective-C had support for generic types so you could specify the expected type of the result of the [`HLDeferred`][HLD]. Since that isn't the case, you should document that information in your header file or elsewhere. 135 | 136 | ### Data Sources ### 137 | 138 | This library includes several concurrent `NSOperation` classes that act as data sources and provide a [`HLDeferred`][HLD] object. 139 | 140 | - [`HLURLDataSource`][HLUDS] fetches the response body of an URL and returns it as `NSData`. 141 | - [`HLDownloadDataSource`][HLDDS] writes the response body of an URL to a file and returns the path. 142 | - [`HLJSONDataSource`][HLJDS] fetches a JSON document from an URL, parses it using [JSONKit][], and returns the represented object. 143 | 144 | ### Using the included data sources ### 145 | 146 | Create a data source operation, then schedule it on an NSOperationQueue by sending it the `-requestStartOnQueue:` message, such as: 147 | 148 | NSOperation *op = [[HLURLDataSource alloc] initWithContext: ctx]; 149 | HLDeferred *d = [op requestStartOnQueue: [NSOperationQueue mainQueue]]; 150 | 151 | **Note:** You don't have to use `[NSOperationQueue mainQueue]`, you can create your own queue and use that. Be aware that `HLDeferredDataSource` executes its [`HLDeferred`][HLD] object's callback chain on the main thread using GCD's `dispatch_async`. 152 | 153 | ### Making your own data sources ### 154 | 155 | See the comments in [HLDeferredDataSource.h](https://github.com/heavylifters/HLDeferred-objc/raw/master/HLDeferred/Classes/HLDeferredDataSource.h) and [HLDeferredConcurrentDataSource.h](https://github.com/heavylifters/HLDeferred-objc/raw/master/HLDeferred/Classes/HLDeferredConcurrentDataSource.h) for more information. 156 | 157 | ### Data Source Example ### 158 | 159 | - (HLDeferred *) requestURLFromString: (NSString *)urlString 160 | { 161 | // Fetch an URL and do something when it's complete 162 | NSOperation *op = [[HLURLDataSource alloc] initWithURLString: urlString]; 163 | NSOperationQueue *queue = [NSOperationQueue mainQueue]; 164 | HLDeferred *d = [op requestStartOnQueue: queue]; 165 | [op release]; 166 | 167 | // the "then" block runs if the operation succeeds 168 | [d then: ^(id result) { 169 | // result is NSData 170 | // download succeeded, do something 171 | return @"SUCCESS!"; 172 | } fail: ^(HLFailure *failure) { // runs if the operations fails 173 | // request failed 174 | return failure; 175 | }]; 176 | return d; 177 | } 178 | 179 | - (void) main 180 | { 181 | HLDeferred *d = [self requestURLFromString: @"http://example.com/"]; 182 | // both means "in the case of success or failure" 183 | [d both: ^(id result) { 184 | // run after the callback specified in requestURLFromString 185 | NSLog(@"result is: %@", [result description]); 186 | return result; 187 | }]; 188 | // perhaps return d. 189 | // The caller could add more callbacks 190 | } 191 | 192 | Composing HLDeferred objects arbitrarily 193 | ---------------------------------------- 194 | 195 | You can return an [`HLDeferred`][HLD] object from the callback or errback of another [`HLDeferred`][HLD] object. If you do, the next link of the callback chain will not be executed until the callback chain of the returned [`HLDeferred`][HLD] is fired. The input to the next link of the original [`HLDeferred`][HLD] object's callback chain will be the output of the returned [`HLDeferred`][HLD] object. 196 | 197 | This effectively builds a dependency tree of [`HLDeferred`][HLD] objects. Using this approach makes it easy to compose arbitrary trees of [`HLDeferred`][HLD] objects without having to manage complicated state machines. 198 | 199 | ### Quick note about memory management ### 200 | 201 | When using a subclass of `HLDeferredDataSource`, memory management is simple; you do not need to explicitly `retain`/`release` the [`HLDeferred`][HLD] provided by `-requestStartOnQueue:`. 202 | 203 | The `HLDeferredDataSource` owns the [`HLDeferred`][HLD] object returned by `-requestStartOnQueue:`. Its callback chain will be fired (on the main thread) prior to the operation being marked as complete. When the operation is marked as complete, the queue `release`s it, which in turn `release`s the [`HLDeferred`][HLD] object. 204 | 205 | As the NSOperationQueue retains the `HLDeferredDataSource` until it is complete, you can safely `release` the data source object once after calling `-requestStartOneQueue:`. 206 | 207 | ### Assemble a firing squad with HLDeferredList ### 208 | 209 | [`HLDeferredList`][HLDL] waits for a list of HLDeferred objects to finish firing before firing its callback chain. 210 | 211 | It can optionally fire when the first result is obtained from the list, or when the first error is encountered, or can consume errors. 212 | 213 | ### Composition example ### 214 | 215 | - (HLDeferred *) requestLogin 216 | { 217 | if ([MyApp isLoggedIn]) { 218 | return [HLDeferred deferredWithResult: @"ok"]; 219 | } else { 220 | NSDictionary *ctx = ...; 221 | NSOperation *op = [[HLDeferredURLRequestConcurrentOperation alloc] initWithContext: ctx]; 222 | NSOperationQueue *queue = [NSOperationQueue mainQueue]; 223 | HLDeferred *d = [op requestStartOnQueue: queue]; 224 | [op release]; 225 | 226 | [d then: ^(id result) { 227 | NSLog(@"login succeeded"); 228 | return @"ok"; 229 | }]; 230 | 231 | return d; 232 | } 233 | } 234 | 235 | // assume these do network requests of some sort 236 | - (HLDeferred *) requestStuff1 { ... } 237 | - (HLDeferred *) requestStuff2 { ... } 238 | 239 | // if successful, the result is a dictionary with keys stuff1 and stuff2 240 | - (HLDeferred *) requestMyStuff 241 | { 242 | // call requestLogin and add a callback to its callback chain 243 | // return that deferred, which the caller can add its own 244 | // callbacks and/or errbacks to. 245 | return [[self requestLogin] then: ^(id result) { 246 | if ([@"ok" isEqualToString: [result description]]) { 247 | NSArray *stuffs = [NSArray arrayWithObjects: 248 | [self requestStuff1], 249 | [self requestStuff2], 250 | nil]; 251 | HLDeferredList *ds = [[HLDeferredList alloc] initWithDeferreds: stuffs 252 | fireOnFirstError: YES]; 253 | [ds then: ^(id result) { 254 | // result is an NSArray containing 2 objects 255 | // - the result of requestStuff1's HLDeferred 256 | // - the result of requestStuff2's HLDeferred 257 | NSDictionary *dict = [[NSDictionary alloc] init]; 258 | [dict setObject: [result objectAtIndex: 0] forKey: @"stuff1"]; 259 | [dict setObject: [result objectAtIndex: 1] forKey: @"stuff2"]; 260 | return [dict autorelease]; 261 | }]; 262 | return [ds autorelease]; 263 | } else { 264 | // returning an exception switches the execution of the 265 | // callback chain from the "then branch" to the "fail branch" 266 | return [HLFailure wrap: result]; 267 | } 268 | }]; 269 | } 270 | 271 | - (void) main 272 | { 273 | [[self requestMyStuff] then: ^(id result) { 274 | // at this point, we know requestStuff1 and requestStuff2 275 | // completed successfully, and result is an NSDictionary 276 | return result; 277 | } fail: (HLFailure *failure) { 278 | // the process failed 279 | return failure; 280 | }] 281 | } 282 | 283 | ### Handling Failure with composition ### 284 | 285 | Unless you require fine-grained handling of failures, specifiy errbacks only in the top-level code that calls the first method returning an [`HLDeferred`][HLD] object. An `IBAction` method is a good example of "top-level code"... 286 | 287 | - (IBAction) signIn: (id)sender 288 | { 289 | [[self requestSignInForUser: userid 290 | withPassword: password] then: ^(id result) { 291 | // success! 292 | return @"ok"; 293 | } fail: (HLFailure *failure) { 294 | // oh noes! 295 | [UIAlertView ...]; 296 | return failure; 297 | }]; 298 | } 299 | 300 | If `-requestSignInForUser:withPassword:` displayed a UIAlertView as well, the user would see multiple alerts! 301 | 302 | There's more (leftovers we haven't written about yet) 303 | ------------ 304 | 305 | HLDeferred also has support for finalizers (which run after the callback chain is exhausted). Check out `-thenFinally:`, `-failFinally:`, `-thenFinally:failFinally:` and `-bothFinally:` in HLDeferred.m for more information. (Eventually we'll write better docs about this - or you can and send us a pull request :-)) 306 | 307 | If you use an `HLDeferredOperation`, you can cancel the operation by sending its [`HLDeferred`][HLD] object the `-cancel` message. `HLDeferredOperation` does this by conforming to the `HLDeferredCancellable` protocol and setting itself as the `cancelTarget` of the [`HLDeferred`][HLD] object - thus it is sent the `-cancel` message when you send `-cancel` to the [`HLDeferred`][HLD] object. 308 | 309 | Also, timeouts are currently supported, but this will probably be removed soon, as we haven't used this functionality. We implemented it because it was part of the Twisted implementation, but since then the timeout functionality has been removed from Twisted as its use was long discouraged. 310 | 311 | Links 312 | ----- 313 | - [Docs](https://github.com/heavylifters/HLDeferred-objc/wiki) (forthcoming) 314 | - [Mailing List](http://groups.google.com/group/hldeferred) 315 | - [Issue Tracker](https://github.com/heavylifters/HLDeferred-objc/issues) (please report bugs and feature requests!) 316 | 317 | How to contribute 318 | ----------------- 319 | - Fork [HLDeferred-objc on GitHub](https://github.com/heavylifters/HLDeferred-objc), send a pull request 320 | 321 | Contributors 322 | ------------ 323 | - [JimRoepcke](https://github.com/JimRoepcke) of [HeavyLifters](https://github.com/heavylifters) 324 | - [samsonjs](https://github.com/samsonjs) of [HeavyLifters](https://github.com/heavylifters) 325 | 326 | Alternatives 327 | ------------ 328 | 329 | - [samuraisam's DeferredKit](https://github.com/samuraisam/DeferredKit) 330 | 331 | Credits 332 | ------- 333 | - Based on [Twisted's Deferred](http://twistedmatrix.com/trac/browser/tags/releases/twisted-10.0.0/twisted/internet/defer.py) classes 334 | - Sponsored by [HeavyLifters Network Ltd.](http://heavylifters.com/) 335 | 336 | License 337 | ------- 338 | 339 | Copyright 2011 [HeavyLifters Network Ltd.](http://heavylifters.com/) Licensed under the terms of the MIT license. See included [LICENSE](https://github.com/heavylifters/HLDeferred-objc/raw/master/LICENSE) file. 340 | 341 | [HLD]: https://github.com/heavylifters/HLDeferred-objc/wiki/HLDeferred 342 | [HLF]: https://github.com/heavylifters/HLDeferred-objc/wiki/HLFailure 343 | [HLDL]: https://github.com/heavylifters/HLDeferred-objc/wiki/HLDeferredList 344 | [HLUDS]: https://github.com/heavylifters/HLDeferred-objc/wiki/HLURLDataSource 345 | [HLDDS]: https://github.com/heavylifters/HLDeferred-objc/wiki/HLDownloadDataSource 346 | [HLJDS]: https://github.com/heavylifters/HLDeferred-objc/wiki/HLJSONDataSource 347 | [JSONKit]: https://github.com/johnezang/JSONKit 348 | [GHUnit]: https://github.com/gabriel/gh-unit 349 | -------------------------------------------------------------------------------- /HLDeferred/HLDeferred.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | 381BBA5313186C330098D5B6 /* JSONKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 381BBA5113186C330098D5B6 /* JSONKit.h */; }; 11 | 381BBA5413186C330098D5B6 /* JSONKit.m in Sources */ = {isa = PBXBuildFile; fileRef = 381BBA5213186C330098D5B6 /* JSONKit.m */; }; 12 | 386E781413D6201100F32E7A /* HLDeferredDataSourceManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 386E781213D6201100F32E7A /* HLDeferredDataSourceManager.h */; }; 13 | 386E781513D6201100F32E7A /* HLDeferredDataSourceManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 386E781313D6201100F32E7A /* HLDeferredDataSourceManager.m */; }; 14 | 388531B51300795D00A256DB /* HLDownloadDataSourceTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 388531B41300795D00A256DB /* HLDownloadDataSourceTest.m */; }; 15 | 388531E013007DAD00A256DB /* HLJSONDataSourceTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 388531DF13007DAD00A256DB /* HLJSONDataSourceTest.m */; }; 16 | 3885A63412FBC56900BA5864 /* HLDeferredDataSourceTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 3885A63312FBC56900BA5864 /* HLDeferredDataSourceTest.m */; }; 17 | 3885A67912FC783000BA5864 /* HLDeferredConcurrentDataSourceTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 3885A67812FC783000BA5864 /* HLDeferredConcurrentDataSourceTest.m */; }; 18 | 3891B76B13D65ED100E5F1C0 /* HLDeferredDataSourceManagerTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 3891B76A13D65ED100E5F1C0 /* HLDeferredDataSourceManagerTest.m */; }; 19 | 38CB29B312FDF0BD00739549 /* HLURLDataSourceTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 38CB29B212FDF0BD00739549 /* HLURLDataSourceTest.m */; }; 20 | A7171D8112F8BBC800FF92BB /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A7171D8012F8BBC800FF92BB /* CoreGraphics.framework */; }; 21 | A7171D8212F8BBC800FF92BB /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AACBBE490F95108600F1A2B1 /* Foundation.framework */; }; 22 | A7171D8412F8BBC800FF92BB /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A7171D8312F8BBC800FF92BB /* UIKit.framework */; }; 23 | A7171D8912F8BBDB00FF92BB /* GHUnitIOS.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A7171D5D12F8BB7C00FF92BB /* GHUnitIOS.framework */; }; 24 | A72B196F12F77215007685CF /* HLDeferred.h in Headers */ = {isa = PBXBuildFile; fileRef = A72B196312F77215007685CF /* HLDeferred.h */; }; 25 | A72B197012F77215007685CF /* HLDeferred.m in Sources */ = {isa = PBXBuildFile; fileRef = A72B196412F77215007685CF /* HLDeferred.m */; }; 26 | A72B197112F77215007685CF /* HLDeferredConcurrentDataSource.h in Headers */ = {isa = PBXBuildFile; fileRef = A72B196512F77215007685CF /* HLDeferredConcurrentDataSource.h */; }; 27 | A72B197212F77215007685CF /* HLDeferredConcurrentDataSource.m in Sources */ = {isa = PBXBuildFile; fileRef = A72B196612F77215007685CF /* HLDeferredConcurrentDataSource.m */; }; 28 | A72B197312F77215007685CF /* HLDownloadDataSource.h in Headers */ = {isa = PBXBuildFile; fileRef = A72B196712F77215007685CF /* HLDownloadDataSource.h */; }; 29 | A72B197412F77215007685CF /* HLDownloadDataSource.m in Sources */ = {isa = PBXBuildFile; fileRef = A72B196812F77215007685CF /* HLDownloadDataSource.m */; }; 30 | A72B197512F77215007685CF /* HLJSONDataSource.h in Headers */ = {isa = PBXBuildFile; fileRef = A72B196912F77215007685CF /* HLJSONDataSource.h */; }; 31 | A72B197712F77215007685CF /* HLDeferredDataSource.h in Headers */ = {isa = PBXBuildFile; fileRef = A72B196B12F77215007685CF /* HLDeferredDataSource.h */; }; 32 | A72B197812F77215007685CF /* HLDeferredDataSource.m in Sources */ = {isa = PBXBuildFile; fileRef = A72B196C12F77215007685CF /* HLDeferredDataSource.m */; }; 33 | A72B197912F77215007685CF /* HLURLDataSource.h in Headers */ = {isa = PBXBuildFile; fileRef = A72B196D12F77215007685CF /* HLURLDataSource.h */; }; 34 | A72B197A12F77215007685CF /* HLURLDataSource.m in Sources */ = {isa = PBXBuildFile; fileRef = A72B196E12F77215007685CF /* HLURLDataSource.m */; }; 35 | A7578F0512FB2E4300D52C21 /* HLFailure.h in Headers */ = {isa = PBXBuildFile; fileRef = A7578F0312FB2E4300D52C21 /* HLFailure.h */; }; 36 | A7578F0612FB2E4300D52C21 /* HLFailure.m in Sources */ = {isa = PBXBuildFile; fileRef = A7578F0412FB2E4300D52C21 /* HLFailure.m */; }; 37 | A75790EE12FB7B3500D52C21 /* HLDeferredListTest.m in Sources */ = {isa = PBXBuildFile; fileRef = A75790ED12FB7B3500D52C21 /* HLDeferredListTest.m */; }; 38 | A757910412FB7C4C00D52C21 /* HLDeferredList.m in Sources */ = {isa = PBXBuildFile; fileRef = A757910312FB7C4C00D52C21 /* HLDeferredList.m */; }; 39 | A757910612FB7C7400D52C21 /* HLDeferredList.h in Headers */ = {isa = PBXBuildFile; fileRef = A757910512FB7C5A00D52C21 /* HLDeferredList.h */; }; 40 | A764F5C812F8C1560002D17E /* libHLDeferred.a in Frameworks */ = {isa = PBXBuildFile; fileRef = D2AAC07E0554694100DB518D /* libHLDeferred.a */; }; 41 | A76B841712F8BD2200ACDD85 /* GHUnitIOSTestMain.m in Sources */ = {isa = PBXBuildFile; fileRef = A76B841612F8BD2200ACDD85 /* GHUnitIOSTestMain.m */; }; 42 | A76B842C12F8BE8000ACDD85 /* HLDeferredTest.m in Sources */ = {isa = PBXBuildFile; fileRef = A76B842B12F8BE8000ACDD85 /* HLDeferredTest.m */; }; 43 | A79B87DD12F9DC410048464F /* HLJSONDataSource.m in Sources */ = {isa = PBXBuildFile; fileRef = A72B196A12F77215007685CF /* HLJSONDataSource.m */; }; 44 | AA747D9F0F9514B9006C5449 /* HLDeferred_Prefix.pch in Headers */ = {isa = PBXBuildFile; fileRef = AA747D9E0F9514B9006C5449 /* HLDeferred_Prefix.pch */; }; 45 | AACBBE4A0F95108600F1A2B1 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AACBBE490F95108600F1A2B1 /* Foundation.framework */; }; 46 | /* End PBXBuildFile section */ 47 | 48 | /* Begin PBXContainerItemProxy section */ 49 | A757912A12FB866C00D52C21 /* PBXContainerItemProxy */ = { 50 | isa = PBXContainerItemProxy; 51 | containerPortal = 0867D690FE84028FC02AAC07 /* Project object */; 52 | proxyType = 1; 53 | remoteGlobalIDString = D2AAC07D0554694100DB518D; 54 | remoteInfo = HLDeferred; 55 | }; 56 | /* End PBXContainerItemProxy section */ 57 | 58 | /* Begin PBXFileReference section */ 59 | 381BBA5113186C330098D5B6 /* JSONKit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = JSONKit.h; path = Classes/JSONKit.h; sourceTree = ""; }; 60 | 381BBA5213186C330098D5B6 /* JSONKit.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JSONKit.m; sourceTree = ""; }; 61 | 386E781213D6201100F32E7A /* HLDeferredDataSourceManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = HLDeferredDataSourceManager.h; path = Classes/HLDeferredDataSourceManager.h; sourceTree = ""; }; 62 | 386E781313D6201100F32E7A /* HLDeferredDataSourceManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HLDeferredDataSourceManager.m; sourceTree = ""; }; 63 | 388531B41300795D00A256DB /* HLDownloadDataSourceTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = HLDownloadDataSourceTest.m; path = Tests/HLDownloadDataSourceTest.m; sourceTree = ""; }; 64 | 388531DF13007DAD00A256DB /* HLJSONDataSourceTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = HLJSONDataSourceTest.m; path = Tests/HLJSONDataSourceTest.m; sourceTree = ""; }; 65 | 3885A63312FBC56900BA5864 /* HLDeferredDataSourceTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = HLDeferredDataSourceTest.m; path = Tests/HLDeferredDataSourceTest.m; sourceTree = ""; }; 66 | 3885A67812FC783000BA5864 /* HLDeferredConcurrentDataSourceTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = HLDeferredConcurrentDataSourceTest.m; path = Tests/HLDeferredConcurrentDataSourceTest.m; sourceTree = ""; }; 67 | 3891B76A13D65ED100E5F1C0 /* HLDeferredDataSourceManagerTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HLDeferredDataSourceManagerTest.m; sourceTree = ""; }; 68 | 38CB29B212FDF0BD00739549 /* HLURLDataSourceTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = HLURLDataSourceTest.m; path = Tests/HLURLDataSourceTest.m; sourceTree = ""; }; 69 | A7171D5D12F8BB7C00FF92BB /* GHUnitIOS.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GHUnitIOS.framework; path = Frameworks/GHUnitIOS.framework; sourceTree = ""; }; 70 | A7171D7A12F8BBA700FF92BB /* Tests.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Tests.app; sourceTree = BUILT_PRODUCTS_DIR; }; 71 | A7171D7C12F8BBA700FF92BB /* HLDeferredTests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = "HLDeferredTests-Info.plist"; path = "Tests/HLDeferredTests-Info.plist"; sourceTree = ""; }; 72 | A7171D8012F8BBC800FF92BB /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; 73 | A7171D8312F8BBC800FF92BB /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; 74 | A72B196312F77215007685CF /* HLDeferred.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = HLDeferred.h; path = Classes/HLDeferred.h; sourceTree = ""; }; 75 | A72B196412F77215007685CF /* HLDeferred.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HLDeferred.m; sourceTree = ""; }; 76 | A72B196512F77215007685CF /* HLDeferredConcurrentDataSource.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = HLDeferredConcurrentDataSource.h; path = Classes/HLDeferredConcurrentDataSource.h; sourceTree = ""; }; 77 | A72B196612F77215007685CF /* HLDeferredConcurrentDataSource.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HLDeferredConcurrentDataSource.m; sourceTree = ""; }; 78 | A72B196712F77215007685CF /* HLDownloadDataSource.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = HLDownloadDataSource.h; path = Classes/HLDownloadDataSource.h; sourceTree = ""; }; 79 | A72B196812F77215007685CF /* HLDownloadDataSource.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HLDownloadDataSource.m; sourceTree = ""; }; 80 | A72B196912F77215007685CF /* HLJSONDataSource.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = HLJSONDataSource.h; path = Classes/HLJSONDataSource.h; sourceTree = ""; }; 81 | A72B196A12F77215007685CF /* HLJSONDataSource.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HLJSONDataSource.m; sourceTree = ""; }; 82 | A72B196B12F77215007685CF /* HLDeferredDataSource.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = HLDeferredDataSource.h; path = Classes/HLDeferredDataSource.h; sourceTree = ""; }; 83 | A72B196C12F77215007685CF /* HLDeferredDataSource.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HLDeferredDataSource.m; sourceTree = ""; }; 84 | A72B196D12F77215007685CF /* HLURLDataSource.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = HLURLDataSource.h; path = Classes/HLURLDataSource.h; sourceTree = ""; }; 85 | A72B196E12F77215007685CF /* HLURLDataSource.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HLURLDataSource.m; sourceTree = ""; }; 86 | A7578F0312FB2E4300D52C21 /* HLFailure.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = HLFailure.h; path = Classes/HLFailure.h; sourceTree = ""; }; 87 | A7578F0412FB2E4300D52C21 /* HLFailure.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HLFailure.m; sourceTree = ""; }; 88 | A75790ED12FB7B3500D52C21 /* HLDeferredListTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = HLDeferredListTest.m; path = Tests/HLDeferredListTest.m; sourceTree = ""; }; 89 | A757910312FB7C4C00D52C21 /* HLDeferredList.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HLDeferredList.m; sourceTree = ""; }; 90 | A757910512FB7C5A00D52C21 /* HLDeferredList.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = HLDeferredList.h; path = Classes/HLDeferredList.h; sourceTree = ""; }; 91 | A76B841612F8BD2200ACDD85 /* GHUnitIOSTestMain.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = GHUnitIOSTestMain.m; path = Tests/GHUnitIOSTestMain.m; sourceTree = ""; }; 92 | A76B841F12F8BD4C00ACDD85 /* HLDeferredTests_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = HLDeferredTests_Prefix.pch; path = Tests/HLDeferredTests_Prefix.pch; sourceTree = ""; }; 93 | A76B842B12F8BE8000ACDD85 /* HLDeferredTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = HLDeferredTest.m; path = Tests/HLDeferredTest.m; sourceTree = ""; }; 94 | AA747D9E0F9514B9006C5449 /* HLDeferred_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HLDeferred_Prefix.pch; sourceTree = SOURCE_ROOT; }; 95 | AACBBE490F95108600F1A2B1 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; 96 | D2AAC07E0554694100DB518D /* libHLDeferred.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libHLDeferred.a; sourceTree = BUILT_PRODUCTS_DIR; }; 97 | /* End PBXFileReference section */ 98 | 99 | /* Begin PBXFrameworksBuildPhase section */ 100 | A7171D7812F8BBA700FF92BB /* Frameworks */ = { 101 | isa = PBXFrameworksBuildPhase; 102 | buildActionMask = 2147483647; 103 | files = ( 104 | A7171D8912F8BBDB00FF92BB /* GHUnitIOS.framework in Frameworks */, 105 | A7171D8112F8BBC800FF92BB /* CoreGraphics.framework in Frameworks */, 106 | A7171D8212F8BBC800FF92BB /* Foundation.framework in Frameworks */, 107 | A7171D8412F8BBC800FF92BB /* UIKit.framework in Frameworks */, 108 | A764F5C812F8C1560002D17E /* libHLDeferred.a in Frameworks */, 109 | ); 110 | runOnlyForDeploymentPostprocessing = 0; 111 | }; 112 | D2AAC07C0554694100DB518D /* Frameworks */ = { 113 | isa = PBXFrameworksBuildPhase; 114 | buildActionMask = 2147483647; 115 | files = ( 116 | AACBBE4A0F95108600F1A2B1 /* Foundation.framework in Frameworks */, 117 | ); 118 | runOnlyForDeploymentPostprocessing = 0; 119 | }; 120 | /* End PBXFrameworksBuildPhase section */ 121 | 122 | /* Begin PBXGroup section */ 123 | 034768DFFF38A50411DB9C8B /* Products */ = { 124 | isa = PBXGroup; 125 | children = ( 126 | D2AAC07E0554694100DB518D /* libHLDeferred.a */, 127 | A7171D7A12F8BBA700FF92BB /* Tests.app */, 128 | ); 129 | name = Products; 130 | sourceTree = ""; 131 | }; 132 | 0867D691FE84028FC02AAC07 /* HLDeferred */ = { 133 | isa = PBXGroup; 134 | children = ( 135 | A79B88AD12FA0D190048464F /* HLDeferred Headers */, 136 | A72B196212F77215007685CF /* Classes */, 137 | 32C88DFF0371C24200C91783 /* Other Sources */, 138 | A76B841512F8BCE500ACDD85 /* Tests */, 139 | 0867D69AFE84028FC02AAC07 /* Frameworks */, 140 | 034768DFFF38A50411DB9C8B /* Products */, 141 | ); 142 | name = HLDeferred; 143 | sourceTree = ""; 144 | }; 145 | 0867D69AFE84028FC02AAC07 /* Frameworks */ = { 146 | isa = PBXGroup; 147 | children = ( 148 | A7171D8312F8BBC800FF92BB /* UIKit.framework */, 149 | A7171D8012F8BBC800FF92BB /* CoreGraphics.framework */, 150 | A7171D5D12F8BB7C00FF92BB /* GHUnitIOS.framework */, 151 | AACBBE490F95108600F1A2B1 /* Foundation.framework */, 152 | ); 153 | name = Frameworks; 154 | sourceTree = ""; 155 | }; 156 | 32C88DFF0371C24200C91783 /* Other Sources */ = { 157 | isa = PBXGroup; 158 | children = ( 159 | AA747D9E0F9514B9006C5449 /* HLDeferred_Prefix.pch */, 160 | ); 161 | name = "Other Sources"; 162 | sourceTree = ""; 163 | }; 164 | A72B196212F77215007685CF /* Classes */ = { 165 | isa = PBXGroup; 166 | children = ( 167 | A79B87F812F9DC610048464F /* Data Sources */, 168 | A72B196412F77215007685CF /* HLDeferred.m */, 169 | A757910312FB7C4C00D52C21 /* HLDeferredList.m */, 170 | 386E781313D6201100F32E7A /* HLDeferredDataSourceManager.m */, 171 | A72B196C12F77215007685CF /* HLDeferredDataSource.m */, 172 | A72B196612F77215007685CF /* HLDeferredConcurrentDataSource.m */, 173 | A7578F0412FB2E4300D52C21 /* HLFailure.m */, 174 | 381BBA5213186C330098D5B6 /* JSONKit.m */, 175 | ); 176 | path = Classes; 177 | sourceTree = ""; 178 | }; 179 | A76B841512F8BCE500ACDD85 /* Tests */ = { 180 | isa = PBXGroup; 181 | children = ( 182 | A7171D7C12F8BBA700FF92BB /* HLDeferredTests-Info.plist */, 183 | A76B841F12F8BD4C00ACDD85 /* HLDeferredTests_Prefix.pch */, 184 | A76B841612F8BD2200ACDD85 /* GHUnitIOSTestMain.m */, 185 | A76B842B12F8BE8000ACDD85 /* HLDeferredTest.m */, 186 | A75790ED12FB7B3500D52C21 /* HLDeferredListTest.m */, 187 | 3891B76A13D65ED100E5F1C0 /* HLDeferredDataSourceManagerTest.m */, 188 | 3885A63312FBC56900BA5864 /* HLDeferredDataSourceTest.m */, 189 | 3885A67812FC783000BA5864 /* HLDeferredConcurrentDataSourceTest.m */, 190 | 38CB29B212FDF0BD00739549 /* HLURLDataSourceTest.m */, 191 | 388531B41300795D00A256DB /* HLDownloadDataSourceTest.m */, 192 | 388531DF13007DAD00A256DB /* HLJSONDataSourceTest.m */, 193 | ); 194 | name = Tests; 195 | sourceTree = ""; 196 | }; 197 | A79B87F812F9DC610048464F /* Data Sources */ = { 198 | isa = PBXGroup; 199 | children = ( 200 | A72B196812F77215007685CF /* HLDownloadDataSource.m */, 201 | A72B196A12F77215007685CF /* HLJSONDataSource.m */, 202 | A72B196E12F77215007685CF /* HLURLDataSource.m */, 203 | ); 204 | name = "Data Sources"; 205 | sourceTree = ""; 206 | }; 207 | A79B88AD12FA0D190048464F /* HLDeferred Headers */ = { 208 | isa = PBXGroup; 209 | children = ( 210 | A72B196712F77215007685CF /* HLDownloadDataSource.h */, 211 | A72B196912F77215007685CF /* HLJSONDataSource.h */, 212 | A72B196D12F77215007685CF /* HLURLDataSource.h */, 213 | A72B196312F77215007685CF /* HLDeferred.h */, 214 | A757910512FB7C5A00D52C21 /* HLDeferredList.h */, 215 | 386E781213D6201100F32E7A /* HLDeferredDataSourceManager.h */, 216 | A72B196B12F77215007685CF /* HLDeferredDataSource.h */, 217 | A72B196512F77215007685CF /* HLDeferredConcurrentDataSource.h */, 218 | A7578F0312FB2E4300D52C21 /* HLFailure.h */, 219 | 381BBA5113186C330098D5B6 /* JSONKit.h */, 220 | ); 221 | name = "HLDeferred Headers"; 222 | sourceTree = ""; 223 | }; 224 | /* End PBXGroup section */ 225 | 226 | /* Begin PBXHeadersBuildPhase section */ 227 | D2AAC07A0554694100DB518D /* Headers */ = { 228 | isa = PBXHeadersBuildPhase; 229 | buildActionMask = 2147483647; 230 | files = ( 231 | AA747D9F0F9514B9006C5449 /* HLDeferred_Prefix.pch in Headers */, 232 | A72B196F12F77215007685CF /* HLDeferred.h in Headers */, 233 | A72B197112F77215007685CF /* HLDeferredConcurrentDataSource.h in Headers */, 234 | A72B197312F77215007685CF /* HLDownloadDataSource.h in Headers */, 235 | A72B197512F77215007685CF /* HLJSONDataSource.h in Headers */, 236 | A72B197712F77215007685CF /* HLDeferredDataSource.h in Headers */, 237 | A72B197912F77215007685CF /* HLURLDataSource.h in Headers */, 238 | A7578F0512FB2E4300D52C21 /* HLFailure.h in Headers */, 239 | A757910612FB7C7400D52C21 /* HLDeferredList.h in Headers */, 240 | 381BBA5313186C330098D5B6 /* JSONKit.h in Headers */, 241 | 386E781413D6201100F32E7A /* HLDeferredDataSourceManager.h in Headers */, 242 | ); 243 | runOnlyForDeploymentPostprocessing = 0; 244 | }; 245 | /* End PBXHeadersBuildPhase section */ 246 | 247 | /* Begin PBXNativeTarget section */ 248 | A7171D7912F8BBA700FF92BB /* HLDeferredTests */ = { 249 | isa = PBXNativeTarget; 250 | buildConfigurationList = A7171D7F12F8BBA800FF92BB /* Build configuration list for PBXNativeTarget "HLDeferredTests" */; 251 | buildPhases = ( 252 | A7171D7612F8BBA700FF92BB /* Resources */, 253 | A7171D7712F8BBA700FF92BB /* Sources */, 254 | A7171D7812F8BBA700FF92BB /* Frameworks */, 255 | ); 256 | buildRules = ( 257 | ); 258 | dependencies = ( 259 | A757912B12FB866C00D52C21 /* PBXTargetDependency */, 260 | ); 261 | name = HLDeferredTests; 262 | productName = Tests; 263 | productReference = A7171D7A12F8BBA700FF92BB /* Tests.app */; 264 | productType = "com.apple.product-type.application"; 265 | }; 266 | D2AAC07D0554694100DB518D /* HLDeferred */ = { 267 | isa = PBXNativeTarget; 268 | buildConfigurationList = 1DEB921E08733DC00010E9CD /* Build configuration list for PBXNativeTarget "HLDeferred" */; 269 | buildPhases = ( 270 | D2AAC07A0554694100DB518D /* Headers */, 271 | D2AAC07B0554694100DB518D /* Sources */, 272 | D2AAC07C0554694100DB518D /* Frameworks */, 273 | ); 274 | buildRules = ( 275 | ); 276 | dependencies = ( 277 | ); 278 | name = HLDeferred; 279 | productName = HLDeferred; 280 | productReference = D2AAC07E0554694100DB518D /* libHLDeferred.a */; 281 | productType = "com.apple.product-type.library.static"; 282 | }; 283 | /* End PBXNativeTarget section */ 284 | 285 | /* Begin PBXProject section */ 286 | 0867D690FE84028FC02AAC07 /* Project object */ = { 287 | isa = PBXProject; 288 | attributes = { 289 | LastUpgradeCheck = 0450; 290 | }; 291 | buildConfigurationList = 1DEB922208733DC00010E9CD /* Build configuration list for PBXProject "HLDeferred" */; 292 | compatibilityVersion = "Xcode 3.2"; 293 | developmentRegion = English; 294 | hasScannedForEncodings = 1; 295 | knownRegions = ( 296 | English, 297 | Japanese, 298 | French, 299 | German, 300 | ); 301 | mainGroup = 0867D691FE84028FC02AAC07 /* HLDeferred */; 302 | productRefGroup = 034768DFFF38A50411DB9C8B /* Products */; 303 | projectDirPath = ""; 304 | projectRoot = ""; 305 | targets = ( 306 | D2AAC07D0554694100DB518D /* HLDeferred */, 307 | A7171D7912F8BBA700FF92BB /* HLDeferredTests */, 308 | ); 309 | }; 310 | /* End PBXProject section */ 311 | 312 | /* Begin PBXResourcesBuildPhase section */ 313 | A7171D7612F8BBA700FF92BB /* Resources */ = { 314 | isa = PBXResourcesBuildPhase; 315 | buildActionMask = 2147483647; 316 | files = ( 317 | ); 318 | runOnlyForDeploymentPostprocessing = 0; 319 | }; 320 | /* End PBXResourcesBuildPhase section */ 321 | 322 | /* Begin PBXSourcesBuildPhase section */ 323 | A7171D7712F8BBA700FF92BB /* Sources */ = { 324 | isa = PBXSourcesBuildPhase; 325 | buildActionMask = 2147483647; 326 | files = ( 327 | A76B841712F8BD2200ACDD85 /* GHUnitIOSTestMain.m in Sources */, 328 | A76B842C12F8BE8000ACDD85 /* HLDeferredTest.m in Sources */, 329 | A75790EE12FB7B3500D52C21 /* HLDeferredListTest.m in Sources */, 330 | 3885A63412FBC56900BA5864 /* HLDeferredDataSourceTest.m in Sources */, 331 | 3885A67912FC783000BA5864 /* HLDeferredConcurrentDataSourceTest.m in Sources */, 332 | 38CB29B312FDF0BD00739549 /* HLURLDataSourceTest.m in Sources */, 333 | 388531B51300795D00A256DB /* HLDownloadDataSourceTest.m in Sources */, 334 | 388531E013007DAD00A256DB /* HLJSONDataSourceTest.m in Sources */, 335 | 3891B76B13D65ED100E5F1C0 /* HLDeferredDataSourceManagerTest.m in Sources */, 336 | ); 337 | runOnlyForDeploymentPostprocessing = 0; 338 | }; 339 | D2AAC07B0554694100DB518D /* Sources */ = { 340 | isa = PBXSourcesBuildPhase; 341 | buildActionMask = 2147483647; 342 | files = ( 343 | A72B197012F77215007685CF /* HLDeferred.m in Sources */, 344 | A757910412FB7C4C00D52C21 /* HLDeferredList.m in Sources */, 345 | A72B197212F77215007685CF /* HLDeferredConcurrentDataSource.m in Sources */, 346 | A72B197412F77215007685CF /* HLDownloadDataSource.m in Sources */, 347 | A72B197812F77215007685CF /* HLDeferredDataSource.m in Sources */, 348 | A72B197A12F77215007685CF /* HLURLDataSource.m in Sources */, 349 | A79B87DD12F9DC410048464F /* HLJSONDataSource.m in Sources */, 350 | A7578F0612FB2E4300D52C21 /* HLFailure.m in Sources */, 351 | 381BBA5413186C330098D5B6 /* JSONKit.m in Sources */, 352 | 386E781513D6201100F32E7A /* HLDeferredDataSourceManager.m in Sources */, 353 | ); 354 | runOnlyForDeploymentPostprocessing = 0; 355 | }; 356 | /* End PBXSourcesBuildPhase section */ 357 | 358 | /* Begin PBXTargetDependency section */ 359 | A757912B12FB866C00D52C21 /* PBXTargetDependency */ = { 360 | isa = PBXTargetDependency; 361 | target = D2AAC07D0554694100DB518D /* HLDeferred */; 362 | targetProxy = A757912A12FB866C00D52C21 /* PBXContainerItemProxy */; 363 | }; 364 | /* End PBXTargetDependency section */ 365 | 366 | /* Begin XCBuildConfiguration section */ 367 | 1DEB921F08733DC00010E9CD /* Debug */ = { 368 | isa = XCBuildConfiguration; 369 | buildSettings = { 370 | ALWAYS_SEARCH_USER_PATHS = NO; 371 | ARCHS = "$(ARCHS_STANDARD_32_BIT)"; 372 | COPY_PHASE_STRIP = NO; 373 | DSTROOT = /tmp/HLDeferred.dst; 374 | FRAMEWORK_SEARCH_PATHS = ( 375 | "$(inherited)", 376 | "\"$(SRCROOT)/Frameworks\"", 377 | ); 378 | GCC_DYNAMIC_NO_PIC = NO; 379 | GCC_MODEL_TUNING = G5; 380 | GCC_OPTIMIZATION_LEVEL = 0; 381 | GCC_PRECOMPILE_PREFIX_HEADER = YES; 382 | GCC_PREFIX_HEADER = HLDeferred_Prefix.pch; 383 | INSTALL_PATH = /usr/local/lib; 384 | PRODUCT_NAME = HLDeferred; 385 | }; 386 | name = Debug; 387 | }; 388 | 1DEB922008733DC00010E9CD /* Release */ = { 389 | isa = XCBuildConfiguration; 390 | buildSettings = { 391 | ALWAYS_SEARCH_USER_PATHS = NO; 392 | ARCHS = "$(ARCHS_STANDARD_32_BIT)"; 393 | DSTROOT = /tmp/HLDeferred.dst; 394 | FRAMEWORK_SEARCH_PATHS = ( 395 | "$(inherited)", 396 | "\"$(SRCROOT)/Frameworks\"", 397 | ); 398 | GCC_MODEL_TUNING = G5; 399 | GCC_PRECOMPILE_PREFIX_HEADER = YES; 400 | GCC_PREFIX_HEADER = HLDeferred_Prefix.pch; 401 | INSTALL_PATH = /usr/local/lib; 402 | PRODUCT_NAME = HLDeferred; 403 | }; 404 | name = Release; 405 | }; 406 | 1DEB922308733DC00010E9CD /* Debug */ = { 407 | isa = XCBuildConfiguration; 408 | buildSettings = { 409 | ARCHS = "$(ARCHS_STANDARD_32_BIT)"; 410 | FRAMEWORK_SEARCH_PATHS = ""; 411 | GCC_C_LANGUAGE_STANDARD = c99; 412 | GCC_OPTIMIZATION_LEVEL = 0; 413 | GCC_VERSION = com.apple.compilers.llvm.clang.1_0; 414 | GCC_WARN_ABOUT_RETURN_TYPE = YES; 415 | GCC_WARN_UNUSED_VARIABLE = YES; 416 | IPHONEOS_DEPLOYMENT_TARGET = 4.0; 417 | OTHER_LDFLAGS = ( 418 | "-ObjC", 419 | "-all_load", 420 | ); 421 | SDKROOT = iphoneos; 422 | TARGETED_DEVICE_FAMILY = "1,2"; 423 | }; 424 | name = Debug; 425 | }; 426 | 1DEB922408733DC00010E9CD /* Release */ = { 427 | isa = XCBuildConfiguration; 428 | buildSettings = { 429 | ARCHS = "$(ARCHS_STANDARD_32_BIT)"; 430 | FRAMEWORK_SEARCH_PATHS = ""; 431 | GCC_C_LANGUAGE_STANDARD = c99; 432 | GCC_PREPROCESSOR_DEFINITIONS = NS_BLOCK_ASSERTIONS; 433 | GCC_VERSION = com.apple.compilers.llvm.clang.1_0; 434 | GCC_WARN_ABOUT_RETURN_TYPE = YES; 435 | GCC_WARN_UNUSED_VARIABLE = YES; 436 | IPHONEOS_DEPLOYMENT_TARGET = 4.0; 437 | OTHER_LDFLAGS = ( 438 | "-ObjC", 439 | "-all_load", 440 | ); 441 | SDKROOT = iphoneos; 442 | TARGETED_DEVICE_FAMILY = "1,2"; 443 | }; 444 | name = Release; 445 | }; 446 | A7171D7D12F8BBA800FF92BB /* Debug */ = { 447 | isa = XCBuildConfiguration; 448 | buildSettings = { 449 | ALWAYS_SEARCH_USER_PATHS = NO; 450 | CODE_SIGN_IDENTITY = "iPhone Developer"; 451 | COPY_PHASE_STRIP = NO; 452 | FRAMEWORK_SEARCH_PATHS = ( 453 | "$(inherited)", 454 | "\"$(SRCROOT)/Frameworks\"", 455 | ); 456 | GCC_DYNAMIC_NO_PIC = NO; 457 | GCC_OPTIMIZATION_LEVEL = 0; 458 | GCC_PRECOMPILE_PREFIX_HEADER = YES; 459 | GCC_PREFIX_HEADER = Tests/HLDeferredTests_Prefix.pch; 460 | INFOPLIST_FILE = "Tests/HLDeferredTests-Info.plist"; 461 | INSTALL_PATH = "$(HOME)/Applications"; 462 | OTHER_LDFLAGS = ( 463 | "-framework", 464 | Foundation, 465 | "-framework", 466 | UIKit, 467 | "-ObjC", 468 | "-all_load", 469 | ); 470 | PRODUCT_NAME = Tests; 471 | SDKROOT = iphoneos; 472 | }; 473 | name = Debug; 474 | }; 475 | A7171D7E12F8BBA800FF92BB /* Release */ = { 476 | isa = XCBuildConfiguration; 477 | buildSettings = { 478 | ALWAYS_SEARCH_USER_PATHS = NO; 479 | CODE_SIGN_IDENTITY = "iPhone Developer"; 480 | COPY_PHASE_STRIP = YES; 481 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 482 | FRAMEWORK_SEARCH_PATHS = ( 483 | "$(inherited)", 484 | "\"$(SRCROOT)/Frameworks\"", 485 | ); 486 | GCC_PRECOMPILE_PREFIX_HEADER = YES; 487 | GCC_PREFIX_HEADER = Tests/HLDeferredTests_Prefix.pch; 488 | INFOPLIST_FILE = "Tests/HLDeferredTests-Info.plist"; 489 | INSTALL_PATH = "$(HOME)/Applications"; 490 | OTHER_LDFLAGS = ( 491 | "-framework", 492 | Foundation, 493 | "-framework", 494 | UIKit, 495 | "-ObjC", 496 | "-all_load", 497 | ); 498 | PRODUCT_NAME = Tests; 499 | SDKROOT = iphoneos; 500 | ZERO_LINK = NO; 501 | }; 502 | name = Release; 503 | }; 504 | /* End XCBuildConfiguration section */ 505 | 506 | /* Begin XCConfigurationList section */ 507 | 1DEB921E08733DC00010E9CD /* Build configuration list for PBXNativeTarget "HLDeferred" */ = { 508 | isa = XCConfigurationList; 509 | buildConfigurations = ( 510 | 1DEB921F08733DC00010E9CD /* Debug */, 511 | 1DEB922008733DC00010E9CD /* Release */, 512 | ); 513 | defaultConfigurationIsVisible = 0; 514 | defaultConfigurationName = Release; 515 | }; 516 | 1DEB922208733DC00010E9CD /* Build configuration list for PBXProject "HLDeferred" */ = { 517 | isa = XCConfigurationList; 518 | buildConfigurations = ( 519 | 1DEB922308733DC00010E9CD /* Debug */, 520 | 1DEB922408733DC00010E9CD /* Release */, 521 | ); 522 | defaultConfigurationIsVisible = 0; 523 | defaultConfigurationName = Release; 524 | }; 525 | A7171D7F12F8BBA800FF92BB /* Build configuration list for PBXNativeTarget "HLDeferredTests" */ = { 526 | isa = XCConfigurationList; 527 | buildConfigurations = ( 528 | A7171D7D12F8BBA800FF92BB /* Debug */, 529 | A7171D7E12F8BBA800FF92BB /* Release */, 530 | ); 531 | defaultConfigurationIsVisible = 0; 532 | defaultConfigurationName = Release; 533 | }; 534 | /* End XCConfigurationList section */ 535 | }; 536 | rootObject = 0867D690FE84028FC02AAC07 /* Project object */; 537 | } 538 | -------------------------------------------------------------------------------- /HLDeferred/Classes/JSONKit/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # JSONKit Changelog 2 | 3 | ## Version 1.X ????/??/?? 4 | 5 | **IMPORTANT:** The following changelog notes are a work in progress. They apply to the work done on JSONKit post v1.4. Since JSONKit itself is inbetween versions, these changelog notes are subject to change, may be wrong, and just about everything else you could expect at this point in development. 6 | 7 | ### New Features 8 | 9 | * When `JKSerializeOptionPretty` is enabled, JSONKit now sorts the keys. 10 | 11 | * Normally, JSONKit can only serialize NSNull, NSNumber, NSString, NSArray, and NSDictioonary like objects. It is now possible to serialize an object of any class via either a delegate or a `^` block. 12 | 13 | The delegate or `^` block must return an object that can be serialized by JSONKit, however, otherwise JSONKit will fail to serialize the object. In other words, JSONKit tries to serialize an unsupported class of the object just once, and if the delegate or ^block returns another unsupported class, the second attempt to serialize will fail. In practice, this is not a problem at all, but it does prevent endless recursive attempts to serialize an unsupported class. 14 | 15 | This makes it trivial to serialize objects like NSDate or NSData. A NSDate object can be formatted using a NSDateFormatter to return a ISO-8601 `YYYY-MM-DDTHH:MM:SS.sssZ` type object, for example. Or a NSData object could be Base64 encoded. 16 | 17 | This greatly simplifies things when you have a complex, nested objects with objects that do not belong to the classes that JSONKit can serialize. 18 | 19 | It should be noted that the same caching that JSONKit does for the supported class types also applies to the objects of an unsupported class- if the same object is serialized more than once and the object is still in the serialization cache, JSONKit will copy the previous serialization result instead of invoking the delegate or `^` block again. Therefore, you should not expect or depend on your delegate or block being called each time the same object needs to be serialized AND the delegate or block MUST return a "formatted object" that is STRICTLY invariant (that is to say the same object must always return the exact same formatted output). 20 | 21 | To serialize NSArray or NSDictionary objects using a delegate– 22 | 23 | **NOTE:** The delegate is based a single argument, the object with the unsupported class, and the supplied `selector` method must be one that accepts a single `id` type argument (i.e., `formatObject:`). 24 | **IMPORTANT:** The `^` block MUST return an object with a class that can be serialized by JSONKit, otherwise the serialization will fail. 25 | 26 |
 27 |     ​- (NSData \*)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError \*\*)error;
 28 |     ​- (NSString \*)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError \*\*)error;
 29 |     
30 | 31 | To serialize NSArray or NSDictionary objects using a `^` block– 32 | 33 | **NOTE:** The block is passed a single argument, the object with the unsupported class. 34 | **IMPORTANT:** The `^` block MUST return an object with a class that can be serialized by JSONKit, otherwise the serialization will fail. 35 | 36 |
 37 |     ​- (NSData \*)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError \*\*)error;
 38 |     ​- (NSString \*)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError \*\*)error;
 39 |     
40 | 41 | Example using the delegate way: 42 | 43 |
 44 |     @interface MYFormatter : NSObject {
 45 |       NSDateFormatter \*outputFormatter;
 46 |     }
 47 |     @end
 48 |     ​
 49 |     @implementation MYFormatter
 50 |     -(id)init
 51 |     {
 52 |       if((self = [super init]) == NULL) { return(NULL); }
 53 |       if((outputFormatter = [[NSDateFormatter alloc] init]) == NULL) { [self autorelease]; return(NULL); }
 54 |       [outputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];
 55 |       return(self);
 56 |     }
 57 |     ​
 58 |     -(void)dealloc
 59 |     {
 60 |       if(outputFormatter != NULL) { [outputFormatter release]; outputFormatter = NULL; }
 61 |       [super dealloc];
 62 |     }
 63 |     ​
 64 |     -(id)formatObject:(id)object
 65 |     {
 66 |       if([object isKindOfClass:[NSDate class]]) { return([outputFormatter stringFromDate:object]); }
 67 |       return(NULL);
 68 |     }
 69 |     @end
 70 |     ​
 71 |     {
 72 |       MYFormatter \*myFormatter = [[[MYFormatter alloc] init] autorelease];
 73 |       NSArray \*array = [NSArray arrayWithObject:[NSDate dateWithTimeIntervalSinceNow:0.0]];
 74 | 
 75 |       NSString \*jsonString = NULL;
 76 |       jsonString = [array                    JSONStringWithOptions:JKSerializeOptionNone
 77 |                           serializeUnsupportedClassesUsingDelegate:myFormatter
 78 |                                                           selector:@selector(formatObject:)
 79 |                                                              error:NULL];
 80 |       NSLog(@"jsonString: '%@'", jsonString);
 81 |       // 2011-03-25 11:42:16.175 formatter_example[59120:903] jsonString: '["2011-03-25T11:42:16.175-0400"]'
 82 |     }
 83 |     
84 | 85 | Example using the `^` block way: 86 | 87 |
 88 |     {
 89 |       NSDateFormatter \*outputFormatter = [[[NSDateFormatter alloc] init] autorelease];
 90 |       [outputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];
 91 |       ​
 92 |       jsonString = [array                 JSONStringWithOptions:encodeOptions
 93 |                           serializeUnsupportedClassesUsingBlock:^id(id object) {
 94 |                             if([object isKindOfClass:[NSDate class]]) { return([outputFormatter stringFromDate:object]); }
 95 |                             return(NULL);
 96 |                           }
 97 |                                                           error:NULL];
 98 |       NSLog(@"jsonString: '%@'", jsonString);
 99 |       // 2011-03-25 11:49:56.434 json_parse[59167:903] jsonString: '["2011-03-25T11:49:56.434-0400"]'
100 |     }
101 |     
102 | 103 | ### Major Changes 104 | 105 | * The way that JSONKit implements the collection classes was modified. Specifically, JSONKit now follows the same strategy that the Cocoa collection classes use, which is to have a single subclass of the mutable collection class. This concrete subclass has an ivar bit that determines whether or not that instance is mutable, and when an immutable instance receives a mutating message, it throws an exception. 106 | 107 | ## Version 1.4 2011/23/03 108 | 109 | ### Highlights 110 | 111 | * JSONKit v1.4 significantly improves the performance of serializing and deserializing. Deserializing is 23% faster than Apples binary `.plist`, and an amazing 549% faster than Apples binary `.plist` when serializing. 112 | 113 | ### New Features 114 | 115 | * JSONKit can now return mutable collection classes. 116 | * The `JKSerializeOptionFlags` option `JKSerializeOptionPretty` was implemented. 117 | * It is now possible to serialize a single [`NSString`][NSString]. This functionality was requested in issue #4 and issue #11. 118 | 119 | ### Deprecated Methods 120 | 121 | * The following `JSONDecoder` methods are deprecated beginning with JSONKit v1.4 and will be removed in a later release– 122 | 123 |
124 |     ​- (id)parseUTF8String:(const unsigned char \*)string length:(size_t)length;
125 |     ​- (id)parseUTF8String:(const unsigned char \*)string length:(size_t)length error:(NSError \*\*)error;
126 |     ​- (id)parseJSONData:(NSData \*)jsonData;
127 |     ​- (id)parseJSONData:(NSData \*)jsonData error:(NSError \*\*)error;
128 |     
129 | 130 | The JSONKit v1.4 objectWith… methods should be used instead. 131 | 132 | ### NEW API's 133 | 134 | * The following methods were added to `JSONDecoder`– 135 | 136 | These methods replace their deprecated parse… counterparts and return immutable collection objects. 137 | 138 |
139 |     ​- (id)objectWithUTF8String:(const unsigned char \*)string length:(NSUInteger)length;
140 |     ​- (id)objectWithUTF8String:(const unsigned char \*)string length:(NSUInteger)length error:(NSError \*\*)error;
141 |     ​- (id)objectWithData:(NSData \*)jsonData;
142 |     ​- (id)objectWithData:(NSData \*)jsonData error:(NSError \*\*)error;
143 |     
144 | 145 | These methods are the same as their objectWith… counterparts except they return mutable collection objects. 146 | 147 |
148 |     ​- (id)mutableObjectWithUTF8String:(const unsigned char \*)string length:(NSUInteger)length;
149 |     ​- (id)mutableObjectWithUTF8String:(const unsigned char \*)string length:(NSUInteger)length error:(NSError \*\*)error;
150 |     ​- (id)mutableObjectWithData:(NSData \*)jsonData;
151 |     ​- (id)mutableObjectWithData:(NSData \*)jsonData error:(NSError \*\*)error;
152 |     
153 | 154 | * The following methods were added to `NSString (JSONKitDeserializing)`– 155 | 156 | These methods are the same as their objectFrom… counterparts except they return mutable collection objects. 157 | 158 |
159 |     ​- (id)mutableObjectFromJSONString;
160 |     ​- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
161 |     ​- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError \*\*)error;
162 |     
163 | 164 | * The following methods were added to `NSData (JSONKitDeserializing)`– 165 | 166 | These methods are the same as their objectFrom… counterparts except they return mutable collection objects. 167 | 168 |
169 |     ​- (id)mutableObjectFromJSONData;
170 |     ​- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
171 |     ​- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError \*\*)error;
172 |     
173 | 174 | * The following methods were added to `NSString (JSONKitSerializing)`– 175 | 176 | These methods are for those uses that need to serialize a single [`NSString`][NSString]– 177 | 178 |
179 |     ​- (NSData \*)JSONData;
180 |     ​- (NSData \*)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError \*\*)error;
181 |     ​- (NSString \*)JSONString;
182 |     ​- (NSString \*)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError \*\*)error;
183 |     
184 | 185 | ### Bug Fixes 186 | 187 | * JSONKit has a fast and a slow path for parsing JSON Strings. The slow path is needed whenever special string processing is required, such as the conversion of `\` escape sequences or ill-formed UTF-8. Although the slow path had a check for characters < `0x20`, which are not permitted by the [RFC 4627][], there was a bug such that the condition was never actually checked. As a result, JSONKit would have incorrectly accepted JSON that contained characters < `0x20` if it was using the slow path to process a JSON String. 188 | * The low surrogate in a \uhigh\ulow escape sequence in a JSON String was incorrectly treating `dfff` as ill-formed Unicode. This was due to a comparison that used `>= 0xdfff` instead of `> 0xdfff` as it should have. 189 | * `JKParseOptionLooseUnicode` was not properly honored when parsing some types of ill-formed Unicode in \uHHHH escapes in JSON Strings. 190 | 191 | ### Important Notes 192 | 193 | * JSONKit v1.4 now uses custom concrete subclasses of [`NSArray`][NSArray], [`NSMutableArray`][NSMutableArray], [`NSDictionary`][NSDictionary], and [`NSMutableDictionary`][NSMutableDictionary]— `JKArray`, `JKMutableArray`, `JKDictionary`, and `JKMutableDictionary`. respectively. These classes are internal and private to JSONKit, you should not instantiate objects from these classes directly. 194 | 195 | In theory, these custom classes should behave exactly the same as the respective Foundation / Cocoa counterparts. 196 | 197 | As usual, in practice may have non-linear excursions from what theory predicts. It is also virtually impossible to properly test or predict how these custom classes will interact with software in the wild. 198 | 199 | Most likely, if you do encounter a problem, it will happen very quickly, and you should report a bug via the [github.com JSONKit Issue Tracker][bugtracker]. 200 | 201 | In addition to the required class cluster primitive methods, the custom collection classes also include support for [`NSFastEnumeration`][NSFastEnumeration], along with methods that support the bulk retrieval of the objects contents. 202 | 203 | #### Exceptions Thrown 204 | 205 | The JSONKit collection classes will throw the same exceptions for the same conditions as their respective Foundation counterparts. If you find a discrepancy, please report a bug via the [github.com JSONKit Issue Tracker][bugtracker]. 206 | 207 | #### Multithreading Safety 208 | 209 | The same multithreading rules and caveats for the Foundation collection classes apply to the JSONKit collection classes. Specifically, it should be safe to use the immutable collections from multiple threads concurrently. 210 | 211 | The mutable collections can be used from multiple threads as long as you provide some form of mutex barrier that ensures that if a thread needs to mutate the collection, then it has exclusive access to the collection– no other thread can be reading from or writing to the collection until the mutating thread has finished. Failure to ensure that there are no other threads reading or writing from the mutable collection when a thread mutates the collection will result in `undefined` behavior. 212 | 213 | #### Mutable Collection Notes 214 | 215 | The mutable versions of the collection classes are meant to be used when you need to make minor modifications to the collection. Neither `JKMutableArray` or `JKMutableDictionary` have been optimized for nor are they intended to be used in situations where you are adding a large number of objects or new keys– these types of operations will cause both classes to frequently reallocate the memory used to hold the objects in the collection. 216 | 217 | #### `JKMutableArray` Usage Notes 218 | 219 | * You should minimize the number of new objects you added to the array. The array is not designed for high performance insertion and removal of objects. If the array does not have any extra capacity it must reallocate the backing store. When the array is forced to grow the backing store, it currently adds an additional 16 slots worth of spare capacity. The array is instantiated without any extra capacity on the assumption that dictionaries are going to be mutated more than arrays. The array never shrinks the backing store. 220 | 221 | * Replacing objects in the array via [`-replaceObjectAtIndex:withObject:`][-replaceObjectAtIndex:withObject:] is very fast since the array simply releases the current object at the index and replaces it with the new object. 222 | 223 | * Inserting an object in to the array via [`-insertObject:atIndex:`][-insertObject:atIndex:] cause the array to [`memmove()`][memmove] all the objects up one slot from the insertion index. This means this operation is fastest when inserting objects at the last index since no objects need to be moved. 224 | 225 | * Removing an object from the array via [`-removeObjectAtIndex:`][-removeObjectAtIndex:] causes the array to [`memmove()`][memmove] all the objects down one slot from the removal index. This means this operation is fastest when removing objects at the last index since no objects need to be moved. The array will not resize its backing store to a smaller size. 226 | 227 | * [`-copy`][-copy] and [`-mutableCopy`][-mutableCopy] will instantiate a new [`NSArray`][NSArray] or [`NSMutableArray`][NSMutableArray] class object, respectively, with the contents of the receiver. 228 | 229 | #### `JKMutableDictionary` Usage Notes 230 | 231 | * You should minimize the number of new keys you add to the dictionary. If the number of items in the dictionary exceeds a threshold value it will trigger a resizing operation. To do this, the dictionary must allocate a new, larger backing store, and then re-add all the items in the dictionary by rehashing them to the size of the newer, larger store. This is an expensive operation. While this is a limitation of nearly all hash tables, the capacity for the hash table used by `JKMutableDictionary` has been chosen to minimize the amount of memory used since it is anticipated that most dictionaries will not grow significantly once they are instantiated. 232 | 233 | * If the key already exists in the dictionary and you change the object associated with it via [`-setObject:forKey:`][-setObject:forKey:], this will not cause any performance problems or trigger a hash table resize. 234 | 235 | * Removing a key from the dictionary via [`-removeObjectForKey:`][-removeObjectForKey:] will not cause any performance problems. However, the dictionary will not resize its backing store to the smaller size. 236 | 237 | * [`-copy`][-copy] and [`-mutableCopy`][-mutableCopy] will instantiate a new [`NSDictionary`][NSDictionary] or [`NSMutableDictionary`][NSMutableDictionary] class object, respectively, with the contents of the receiver. 238 | 239 | ### Major Changes 240 | 241 | * The `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` pre-processor define flag that was added to JSONKit v1.3 has been removed. 242 | 243 | `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` was added in JSONKit v1.3 as a temporary work around. While the author was aware of other ways to fix the particular problem caused by the usage of "transfer of ownership callbacks" with Core Foundation classes, the fix provided in JSONKit v1.3 was trivial to implement. This allowed people who needed that functionality to use JSONKit while a proper solution to the problem was worked on. JSONKit v1.4 is the result of that work. 244 | 245 | JSONKit v1.4 no longer uses the Core Foundation collection classes [`CFArray`][CFArray] and [`CFDictionary`][CFDictionary]. Instead, JSONKit v1.4 contains a concrete subclass of [`NSArray`][NSArray] and [`NSDictionary`][NSDictionary]– `JKArray` and `JKDictionary`, respectively. As a result, JSONKit has complete control over the behavior of how items are added and managed within an instantiated collection object. The `JKArray` and `JKDictionary` classes are private to JSONKit, you should not instantiate them direction. Since they are concrete subclasses of their respective collection class cluster, they behave and act exactly the same as [`NSArray`][NSArray] and [`NSDictionary`][NSDictionary]. 246 | 247 | The first benefit is that the "transfer of ownership" object ownership policy can now be safely used. Because the JSONKit collection objects understand that some methods, such as [`-mutableCopy`][-mutableCopy], should not inherit the same "transfer of ownership" object ownership policy, but must follow the standard Cocoa object ownership policy. The "transfer of ownership" object ownership policy reduces the number of [`-retain`][-retain] and [`-release`][-release] calls needed to add an object to a collection, and when creating a large number of objects very quickly (as you would expect when parsing JSON), this can result in a non-trivial amount of time. Eliminating these calls means faster JSON parsing. 248 | 249 | A second benefit is that the author encountered some unexpected behavior when using the [`CFDictionaryCreate`][CFDictionaryCreate] function to create a dictionary and the `keys` argument contained duplicate keys. This required JSONKit to de-duplicate the keys and values before calling [`CFDictionaryCreate`][CFDictionaryCreate]. Unfortunately, JSONKit always had to scan all the keys to make sure there were no duplicates, even though 99.99% of the time there were none. This was less than optimal, particularly because one of the solutions to this particular problem is to use a hash table to perform the de-duplication. Now JSONKit can do the de-duplication while it is instantiating the dictionary collection, solving two problems at once. 250 | 251 | Yet another benefit is that the recently instantiated object cache that JSONKit uses can be used to cache information about the keys used to create dictionary collections, in particular a keys [`-hash`][-hash] value. For a lot of real world JSON, this effectively means that the [`-hash`][-hash] for a key is calculated once, and that value is reused again and again when creating dictionaries. Because all the information required to create the hash table used by `JKDictionary` is already determined at the time the `JKDictionary` object is instantiated, populating the `JKDictionary` is now a very tight loop that only has to call [`-isEqual:`][-isEqual:] on the rare occasions that the JSON being parsed contains duplicate keys. Since the functions that handle this logic are all declared `static` and are internal to JSONKit, the compiler can heavily optimize this code. 252 | 253 | What does this mean in terms of performance? JSONKit was already fast, but now, it's even faster. Below is some benchmark times for [`twitter_public_timeline.json`][twitter_public_timeline.json] in [samsoffes / json-benchmarks](https://github.com/samsoffes/json-benchmarks), where _read_ means to convert the JSON to native Objective-C objects, and _write_ means to convert the native Objective-C to JSON— 254 | 255 |
256 |     v1.3 read : min:  456.000 us, avg:  460.056 us, char/s:  53341332.36 /  50.870 MB/s
257 |     v1.3 write: min:  150.000 us, avg:  151.816 us, char/s: 161643041.58 / 154.155 MB/s
258 | 259 |
260 |     v1.4 read : min:  285.000 us, avg:  288.603 us, char/s:  85030301.14 /  81.091 MB/s
261 |     v1.4 write: min:  127.000 us, avg:  129.617 us, char/s: 189327017.29 / 180.556 MB/s
262 | 263 | JSONKit v1.4 is nearly 60% faster at reading and 17% faster at writing than v1.3. 264 | 265 | The following is the JSON test file taken from the project available at [this blog post](http://psionides.jogger.pl/2010/12/12/cocoa-json-parsing-libraries-part-2/). The keys and information contained in the JSON was anonymized with random characters. Since JSONKit relies on its recently instantiated object cache for a lot of its performance, this JSON happens to be "the worst corner case possible". 266 | 267 |
268 |     v1.3 read : min: 5222.000 us, avg: 5262.344 us, char/s:  15585260.10 /  14.863 MB/s
269 |     v1.3 write: min: 1253.000 us, avg: 1259.914 us, char/s:  65095712.88 /  62.080 MB/s
270 | 271 |
272 |     v1.4 read : min: 4096.000 us, avg: 4122.240 us, char/s:  19895736.30 /  18.974 MB/s
273 |     v1.4 write: min: 1319.000 us, avg: 1335.538 us, char/s:  61409709.05 /  58.565 MB/s
274 | 275 | JSONKit v1.4 is 28% faster at reading and 6% faster at writing that v1.3 in this worst-case torture test. 276 | 277 | While your milage may vary, you will likely see improvements in the 50% for reading and 10% for writing on your real world JSON. The nature of JSONKits cache means performance improvements is statistical in nature and depends on the particular properties of the JSON being parsed. 278 | 279 | For comparison, [json-framework][], a popular Objective-C JSON parsing library, turns in the following benchmark times for [`twitter_public_timeline.json`][twitter_public_timeline.json]— 280 | 281 |
282 |     ​     read : min: 1670.000 us, avg: 1682.461 us, char/s:  14585776.43 /  13.910 MB/s
283 |     ​     write: min: 1021.000 us, avg: 1028.970 us, char/s:  23849091.81 /  22.744 MB/s
284 | 285 | Since the benchmark for JSONKit and [json-framework][] was done on the same computer, it's safe to compare the timing results. The version of [json-framework][] used was the latest v3.0 available via the master branch at the time of this writing on github.com. 286 | 287 | JSONKit v1.4 is 483% faster at reading and 694% faster at writing than [json-framework][]. 288 | 289 | ### Other Changes 290 | 291 | * Added a `__clang_analyzer__` pre-processor conditional around some code that the `clang` static analyzer was giving false positives for. However, `clang` versions ≤ 1.5 do not define `__clang_analyzer__` and therefore will continue to emit analyzer warnings. 292 | * The cache now uses a Galois Linear Feedback Shift Register PRNG to select which item in the cache to randomly age. This should age items in the cache more fairly. 293 | * To promote better L1 cache locality, the cache age structure was rearranged slightly along with modifying when an item is randomly chosen to be aged. 294 | * Removed a lot of internal and private data structures from `JSONKit.h` and put them in `JSONKit.m`. 295 | * Modified the way floating point values are serialized. Previously, the [`printf`][printf] format conversion `%.16g` was used. This was changed to `%.17g` which should theoretically allow for up to a full `float`, or [IEEE 754 Single 32-bit floating-point][Single Precision], of precision when converting floating point values to decimal representation. 296 | * The usual sundry of inconsequential tidies and what not, such as updating the `README.md`, etc. 297 | * The catagory additions to the Cocoa classes were changed from `JSONKit` to `JSONKitDeserializing` and `JSONKitSerializing`, as appropriate. 298 | 299 | ## Version 1.3 2011/05/02 300 | 301 | ### New Features 302 | 303 | * Added the `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` pre-processor define flag. 304 | 305 | This is typically enabled by adding `-DJK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` to the compilers command line arguments or in `Xcode.app` by adding `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` to a projects / targets `Pre-Processor Macros` settings. 306 | 307 | The `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` option enables the use of custom Core Foundation collection call backs which omit the [`CFRetain`][CFRetain] calls. This results in saving several [`CFRetain`][CFRetain] and [`CFRelease`][CFRelease] calls typically needed for every single object from the parsed JSON. While the author has used this technique for years without any issues, an unexpected interaction with the Foundation [`-mutableCopy`][-mutableCopy] method and Core Foundation Toll-Free Bridging resulting in a condition in which the objects contained in the collection to be over released. This problem does not occur with the use of [`-copy`][-copy] due to the fact that the objects created by JSONKit are immutable, and therefore [`-copy`][-copy] does not require creating a completely new object and copying the contents, instead [`-copy`][-copy] simply returns a [`-retain`][-retain]'d version of the immutable object which is significantly faster along with the obvious reduction in memory usage. 308 | 309 | Prior to version 1.3, JSONKit always used custom "Transfer of Ownership Collection Callbacks", and thus `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` was effectively implicitly defined. 310 | 311 | Beginning with version 1.3, the default behavior of JSONKit is to use the standard Core Foundation collection callbacks ([`kCFTypeArrayCallBacks`][kCFTypeArrayCallBacks], [`kCFTypeDictionaryKeyCallBacks`][kCFTypeDictionaryKeyCallBacks], and [`kCFTypeDictionaryValueCallBacks`][kCFTypeDictionaryValueCallBacks]). The intention is to follow "the principle of least surprise", and the author believes the use of the standard Core Foundation collection callbacks as the default behavior for JSONKit results in the least surprise. 312 | 313 | **NOTE**: `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` is only applicable to `(CF|NS)` `Dictionary` and `Array` class objects. 314 | 315 | For the vast majority of users, the author believes JSONKits custom "Transfer of Ownership Collection Callbacks" will not cause any problems. As previously stated, the author has used this technique in performance critical code for years and has never had a problem. Until a user reported a problem with [`-mutableCopy`][-mutableCopy], the author was unaware that the use of the custom callbacks could even cause a problem. This is probably due to the fact that the vast majority of time the typical usage pattern tends to be "iterate the contents of the collection" and very rarely mutate the returned collection directly (although this last part is likely to vary significantly from programmer to programmer). The author tends to avoid the use of [`-mutableCopy`][-mutableCopy] as it results in a significant performance and memory consumption penalty. The reason for this is in "typical" Cocoa coding patterns, using [`-mutableCopy`][-mutableCopy] will instantiate an identical, albeit mutable, version of the original object. This requires both memory for the new object and time to iterate the contents of the original object and add them to the new object. Furthermore, under "typical" Cocoa coding patterns, the original collection object continues to consume memory until the autorelease pool is released. However, clearly there are cases where the use of [`-mutableCopy`][-mutableCopy] makes sense or may be used by an external library which is out of your direct control. 316 | 317 | The use of the standard Core Foundation collection callbacks results in a 9% to 23% reduction in parsing performance, with an "eye-balled average" of around 13% according to some benchmarking done by the author using Real World™ JSON (i.e., actual JSON from various web services, such as Twitter, etc) using `gcc-4.2 -arch x86_64 -O3 -DNS_BLOCK_ASSERTIONS` with the only change being the addition of `-DJK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS`. 318 | 319 | `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS` is only applicable to parsing / deserializing (i.e. converting from) of JSON. Serializing (i.e., converting to JSON) is completely unaffected by this change. 320 | 321 | ### Bug Fixes 322 | 323 | * Fixed a [bug report regarding `-mutableCopy`](https://github.com/johnezang/JSONKit/issues#issue/3). This is related to the addition of the pre-processor define flag `JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS`. 324 | 325 | ### Other Changes 326 | 327 | * Added `JK_EXPECTED` optimization hints around several conditionals. 328 | * When serializing objects, JSONKit first starts with a small, on stack buffer. If the encoded JSON exceeds the size of the stack buffer, JSONKit switches to a heap allocated buffer. If JSONKit switched to a heap allocated buffer, [`CFDataCreateWithBytesNoCopy`][CFDataCreateWithBytesNoCopy] is used to create the [`NSData`][NSData] object, which in most cases causes the heap allocated buffer to "transfer" to the [`NSData`][NSData] object which is substantially faster than allocating a new buffer and copying the bytes. 329 | * Added a pre-processor check in `JSONKit.m` to see if Objective-C Garbage Collection is enabled and issue a `#error` notice that JSONKit does not support Objective-C Garbage Collection. 330 | * Various other minor or trivial modifications, such as updating `README.md`. 331 | 332 | ### Other Issues 333 | 334 | * When using the `clang` static analyzer (the version used at the time of this writing was `Apple clang version 1.5 (tags/Apple/clang-60)`), the static analyzer reports a number of problems with `JSONKit.m`. 335 | 336 | The author has investigated these issues and determined that the problems reported by the current version of the static analyzer are "false positives". Not only that, the reported problems are not only "false positives", they are very clearly and obviously wrong. Therefore, the author has made the decision that no action will be taken on these non-problems, which includes not modifying the code for the sole purpose of silencing the static analyzer. The justification for this is "the dog wags the tail, not the other way around." 337 | 338 | ## Version 1.2 2011/01/08 339 | 340 | ### Bug Fixes 341 | 342 | * When JSONKit attempted to parse and decode JSON that contained `{"key": value}` dictionaries that contained the same key more than once would likely result in a crash. This was a serious bug. 343 | * Under some conditions, JSONKit could potentially leak memory. 344 | * There was an off by one error in the code that checked whether or not the parser was at the end of the `UTF8` buffer. This could result in JSONKit reading one by past the buffer bounds in some cases. 345 | 346 | ### Other Changes 347 | 348 | * Some of the methods were missing `NULL` pointer checks for some of their arguments. This was fixed. In generally, when JSONKit encounters invalid arguments, it throws a `NSInvalidArgumentException` exception. 349 | * Various other minor changes such as tightening up numeric literals with `UL` or `L` qualification, assertion check tweaks and additions, etc. 350 | * The README.md file was updated with additional information. 351 | 352 | ### Version 1.1 353 | 354 | No change log information was kept for versions prior to 1.2. 355 | 356 | [bugtracker]: https://github.com/johnezang/JSONKit/issues 357 | [RFC 4627]: http://tools.ietf.org/html/rfc4627 358 | [twitter_public_timeline.json]: https://github.com/samsoffes/json-benchmarks/blob/master/Resources/twitter_public_timeline.json 359 | [json-framework]: https://github.com/stig/json-framework 360 | [Single Precision]: http://en.wikipedia.org/wiki/Single_precision 361 | [kCFTypeArrayCallBacks]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFArrayRef/Reference/reference.html#//apple_ref/c/data/kCFTypeArrayCallBacks 362 | [kCFTypeDictionaryKeyCallBacks]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html#//apple_ref/c/data/kCFTypeDictionaryKeyCallBacks 363 | [kCFTypeDictionaryValueCallBacks]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html#//apple_ref/c/data/kCFTypeDictionaryValueCallBacks 364 | [CFRetain]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFTypeRef/Reference/reference.html#//apple_ref/c/func/CFRetain 365 | [CFRelease]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFTypeRef/Reference/reference.html#//apple_ref/c/func/CFRelease 366 | [CFDataCreateWithBytesNoCopy]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFDataRef/Reference/reference.html#//apple_ref/c/func/CFDataCreateWithBytesNoCopy 367 | [CFArray]: http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFArrayRef/Reference/reference.html 368 | [CFDictionary]: http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html 369 | [CFDictionaryCreate]: http://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html#//apple_ref/c/func/CFDictionaryCreate 370 | [-mutableCopy]: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html%23//apple_ref/occ/instm/NSObject/mutableCopy 371 | [-copy]: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html%23//apple_ref/occ/instm/NSObject/copy 372 | [-retain]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/retain 373 | [-release]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/release 374 | [-isEqual:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/isEqual: 375 | [-hash]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/hash 376 | [NSArray]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/index.html 377 | [NSMutableArray]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/index.html 378 | [-insertObject:atIndex:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/insertObject:atIndex: 379 | [-removeObjectAtIndex:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/removeObjectAtIndex: 380 | [-replaceObjectAtIndex:withObject:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/replaceObjectAtIndex:withObject: 381 | [NSDictionary]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/index.html 382 | [NSMutableDictionary]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/index.html 383 | [-setObject:forKey:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableDictionary/setObject:forKey: 384 | [-removeObjectForKey:]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableDictionary/removeObjectForKey: 385 | [NSData]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/index.html 386 | [NSFastEnumeration]: http://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSFastEnumeration_protocol/Reference/NSFastEnumeration.html 387 | [NSString]: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html 388 | [printf]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/printf.3.html 389 | [memmove]: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/memmove.3.html 390 | --------------------------------------------------------------------------------