summaryrefslogtreecommitdiffstats
path: root/Classes/Source/Experimental/CJSONDeserializer_BlocksExtensions.m
blob: 7ea774c435a9ef9a449fb82076cc54cdd3a712a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//
//  CJSONDeserializer_BlocksExtensions.m
//  TouchJSON
//
//  Created by Jonathan Wight on 10/15/10.
//  Copyright 2010 toxicsoftware.com. All rights reserved.
//

#import "CJSONDeserializer_BlocksExtensions.h"

#import "CJSONScanner.h"

@implementation CJSONDeserializer (CJSONDeserializer_BlocksExtensions)

- (void)deserializeAsDictionary:(NSData *)inData completionBlock:(void (^)(id result, NSError *error))block {
	
	NSError *noDataError = nil;
	if (inData == NULL || [inData length] == 0) {
		noDataError = [NSError errorWithDomain:kJSONDeserializerErrorDomain code:kJSONScannerErrorCode_NothingToScan userInfo:NULL];
		block(nil, noDataError);
	}
	
	[[NSOperationQueue mainQueue] addOperationWithBlock:^{
		
		NSError *deserializationError = nil;
		self.scanner.data = inData;
		NSDictionary *theDictionary = NULL;
		BOOL successful = [self.scanner scanJSONDictionary:&theDictionary error:&deserializationError];
		
		dispatch_async(dispatch_get_main_queue (), ^{
			if (successful)
				block(theDictionary, nil);
			else
				block(nil, deserializationError);
		});
	}];
}

- (void)deserializeAsArray:(NSData *)inData completionBlock:(void (^)(id result, NSError *error))block {
	
	NSError *nullInDataError = nil;
	if (inData == NULL || [inData length] == 0) {
		nullInDataError = [NSError errorWithDomain:kJSONDeserializerErrorDomain code:kJSONScannerErrorCode_NothingToScan userInfo:NULL];
		block(nil, nullInDataError);
	}
			  
	[[NSOperationQueue mainQueue] addOperationWithBlock:^{
		
		NSError *deserializationError = nil;
        self.scanner.data = inData;
		NSArray *theArray = NULL;
		BOOL successful = [self.scanner scanJSONArray:&theArray error:&deserializationError];
		
		dispatch_async(dispatch_get_main_queue(), ^{
			if (successful)
				block(theArray, nil);
			else
				block(nil, deserializationError);
		});
	}];
}

@end