I am new to objective C and trying to develop my own callback function, the callback function gets called on a particular event like receiving data from network like NSURLprotocol
does and once received it will NSLog a message that "Event has Occured" or display as text on UIViewController
or any UI related action.
So, I am totally confused as to where the eventOccuredMethod
should be called to let the receiveController
be called and execute the implementation inside it.
I have used protocols like NSURLProtocol
before, but I don't know how to implement them to get such callbacks being called.
Any video links, answers, articles links are welcomed.
//Sample.h file
#import <Foundation/Foundation.h>
@class Sample;
@protocol SampleProtocol <NSObject>
-(void)receivedCallback;
@end
@interface Sample : NSObject
@property (nonatomic,weak) id<SampleProtocol> delegate;
-(void)eventOccured;
@end
//Sample.m file
#import "Sample.h"
@implementation Sample
-(void)eventOccured{
if([_delegate conformsToProtocol:@protocol(SampleProtocol)])
[_delegate receivedCallback];
}
@end
//ViewController.h file
@interface ViewController : UIViewController<SampleProtocol>
@end
//ViewController.m file
#import "ViewController.h"
@interface ViewController (){
Sample *s;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
s = [[Sample alloc] init];
s.delegate = self;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)receivedCallback:(Sample *)sample{
NSLog(@"Event Has Occured");
}
@end
I am not sure of the following call which I am making ...
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
Sample *s = [[Sample alloc] init];
[s eventOccured];
}