json rpc - How to store blocks in Objective C? -


i started writing simple json rpc tcp library in objective c. have method invokes rpc method:

- (void)invokemethod:(nsstring *)method       withparameters:(id)parameters            requestid:(id)requestid              success:(void (^)(id responseobject))success              failure:(void (^)(nserror *error))failure {     nsassert(nsclassfromstring(@"nsjsonserialization"), @"nsjsonserialization not found!");     nsdictionary *requestobject = @{@"jsonrpc": @"2.0",                                     @"method": method,                                     @"params": parameters,                                     @"id": requestid};     nserror *error = nil;     nsdata *jsonddata = [nsjsonserialization datawithjsonobject:requestobject options:0 error:&error];     if (error){         return failure(error);     }     [self->callbacks setobject:@{@"success": success ? [success copy] : [nsnull null],                                  @"failure": failure ? [failure copy] : [nsnull null]}                         forkey:requestid];     nsstring *str = [[nsstring alloc] initwithdata:jsonddata encoding:nsutf8stringencoding];     nslog(@"sending: %@", str);     [self.socket writedata:jsonddata withtimeout:-1 tag:1]; } 

the class represents tcp connection, when calling above method, json data sent id on tcp server either returns success or failure:

- (void) socket:(gcdasyncsocket *)sender didreaddata:(nsdata *)data withtag:(long)tag {     nserror *error = nil;     [self.socket readdatawithtimeout:-1 tag:2];     // … rpc response parsing code here, removed simplicity …     // detect if error or success     nsdictionary *cbs = [self->callbacks objectforkey:jsonrpcobjectid];     void(^success)(id resultobject) = [cbs objectforkey:@"success"];     success ? success(jsonrpcobjectresult) : nil;     return; } 

now, unsure how keep track of success , failure blocks, storing them in nsmutabledict, using requestid key. fine or there better approach should use?

blocks in objective-c objects , can treat same way other object, storing them in nsdictionarys, nsarrays etc fine. catch blocks when created exist in same memory scope local variable , no longer valid when method block defined in returns, other local variables have copy them first, copy them , put copy in collection. there block copy function can send them copy message [myblock copy];


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -