Reputation: 4695
I am working on an iOS app. I have created a class that pulls data off of a server. However when the request receives the data I need to call a method inside a view controller that created the instance of the class.
Request.m
- (id)initWithDictionary:(NSMutableDictionary *)dict
{
if (self = [super init]) {
[[API sharedInstance] commandWithParams:dict onCompletion:^(NSDictionary *json) {
for (NSString* key in json) {
//call method in view controller
}];
}
return self;
}
In some view controller:
//how I submit the request
Request *myRequest = [[Request alloc] initWithDictionary:myDict];
//the method I need to call onCompletion:
- (void)receivedRequest{}
If someone could give me onsite on how to do this I would greatly appreciate it!
Upvotes: 0
Views: 1344
Reputation: 57060
Another approach to delegation is the use of block-based API which is more convenient depending on the scenario.
- (id)initWithDictionary:(NSMutableDictionary *)dict requestCompletionHandler:(void(^)(NSString*, id))completionHandler
{
if (self = [super init]) {
[[API sharedInstance] commandWithParams:dict onCompletion:^(NSDictionary *json) {
if(completionHandler == nil) return;
for (NSString* key in json) {
completionHandler(key, json[key]);
}];
}
return self;
}
But I would recommend implementing in a slightly different approach. You should not execute your request in its init
methods, but rather after calling a start
method.
Upvotes: 1
Reputation: 131511
This is a textbook application for the delegate design pattern:
Set up a protocol. Let's call it requestProtocol.
Define the methods that the Request object will need to call in the request protocol.
Give your Request class a delegate property. Set up the delegate to conform to your requestProtocol.
When your view controller creates a request object, have it set itself as the delegate.
(This means that your view controller will need to conform to your requestProtocol)
in your Request object, when you start parsing the JSON keys, call the delegate's receivedRequest method.
Upvotes: 3