Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // RW3PastPriceItemsOperation.m
- // Pecos
- //
- // Created by Vitaly Dyachkov on 27.05.15.
- // Copyright (c) 2015 Vitaly Dyachkov. All rights reserved.
- //
- #import "RW3PastPriceItemsOperation.h"
- #import "RW3PastPriceItem.h"
- #define BUFFER_SIZE 500
- @interface RW3PastPriceItemsOperation ()
- @property (nonatomic, readonly) NSManagedObjectContext *context;
- @property (nonatomic, readonly) NSMutableArray *items;
- @property (nonatomic, readonly) NSMutableDictionary *buffer;
- @property (nonatomic, strong) NSArray *alternatviePriceReasons;
- @end
- @implementation RW3PastPriceItemsOperation
- - (instancetype)initWithRequest:(NSURLRequest *)request context:(NSManagedObjectContext *)context
- {
- self = [super initWithRequest:request];
- if (self) {
- RW3LogNormal();
- _context = context;
- _items = [[NSMutableArray alloc] init];
- _buffer = [[NSMutableDictionary alloc] initWithCapacity:BUFFER_SIZE];
- __weak __typeof(self) weakSelf = self;
- [self setProcessingBlock:^(NSDictionary *JSONObject) {
- __strong __typeof(self) strongSelf = weakSelf;
- if (!strongSelf.alternatviePriceReasons) {
- [strongSelf.context performBlockAndWait:^{
- NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"AlternativePriceReason"];
- NSError *error = nil;
- strongSelf.alternatviePriceReasons = [context executeFetchRequest:request error:&error];
- if (!strongSelf.alternatviePriceReasons) {
- RW3LogError(@"Error occurred while executing fetch request: %@", error);
- }
- }];
- }
- NSString *upc = JSONObject[@"Upc"];
- strongSelf.buffer[upc] = JSONObject;
- if ([strongSelf.buffer count] == BUFFER_SIZE) {
- [strongSelf processBufferedItems];
- }
- }];
- }
- return self;
- }
- - (void)processBufferedItems
- {
- NSManagedObjectContext *context = self.context;
- [context performBlockAndWait:^{
- for (NSString *upc in [self.buffer allKeys]) {
- RW3PastPriceItem *item = [NSEntityDescription insertNewObjectForEntityForName:@"PastPriceItem" inManagedObjectContext:context];
- NSDictionary *JSONObject = self.buffer[upc];
- [item populateWithJSON:JSONObject alternativePriceReasons:self.alternatviePriceReasons];
- [self.items addObject:item];
- }
- }];
- [self.buffer removeAllObjects];
- }
- - (void)setCompletionBlockWithSuccess:(void (^)(NSArray *items))success failure:(void (^)(NSError *error))failure
- {
- [super setCompletionBlockWithSuccess:^(RW3JSONRequestOperation *operation) {
- RW3PastPriceItemsOperation *pastPriceItemsOperation = (RW3PastPriceItemsOperation *)operation;
- [pastPriceItemsOperation processBufferedItems];
- RW3LogNormal(@"Processed %lu past price items.", (unsigned long)pastPriceItemsOperation.items.count);
- success(pastPriceItemsOperation.items);
- } failure:^(RW3JSONRequestOperation *operation, NSError *error) {
- failure(error);
- }];
- }
- @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement