I want to develop Custom Connection Class by which I can make API calls using it. I do not want to use any third party apis like afhttprequest or asihttp.
I want to develop my self this type of delegate. I have searched much things but I do not have much idea in CustomDelegates.
I wrote one example of custom delegate.
From ViewController.m we call method with two number for addition of another class (Addition class)
Addition class will add these two number and call delegate method so we can get answer of that two number in ViewController using custom delegate.
Addition.h
#import <Foundation/Foundation.h>
// write protocal for this class
// you can give any name of that protocol
#protocol AdditionDelgate <NSObject>
// delegate method of this delegate
-(void)answerOfTwoNumberAddition:(int)ans;
#end
#interface Addition : NSObject
{
}
// set property of that protocol, so using that we can call that protocol methods (i.e. ansOfYourAns)
#property (nonatomic, weak) id <AdditionDelgate> delegate;
-(void) addThisNumber:(int) firstNumber withSecondNumber:(int)secondNumber;
#end
Addition.m
#import "Addition.h"
#implementation Addition
-(void)addThisNumber:(int)firstNumber withSecondNumber:(int)secondNumber
{
int ans = firstNumber + secondNumber;
// call delegate method of "AdditionDelgate" protocol
// we already set delegate of viewController to this protocol
// so it will call viewController class "answerOfTwoNumberAddition" method
[self.delegate answerOfTwoNumberAddition:ans];
}
#end
ViewController.h
#import <UIKit/UIKit.h>
// import addition class
#import "Addition.h"
// set AdditionDelgate to class
#interface ViewController : UIViewController <AdditionDelgate>
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// creat object of class
Addition * additionObj = [[Addition alloc] init];
// set delegate as self to that so that methods delegate methods will call
additionObj.delegate = self;
// call method
[additionObj addThisNumber:2 withSecondNumber:3];
}
#pragma mark ----- Delegate method of Addition view ----
// this is delegate method of Addition class, it will call from "addThisNumber" method line of code
// ([self.delegate answerOfTwoNumberAddition:ans];)
-(void)answerOfTwoNumberAddition:(int)ans
{
NSLog(#"addition of two number is %d",ans);
}
#end
I hope it will help you
Related
I have written protocol in a view controller, and implement it in AppDelegate, and when I call delegate function from view controller, the delegate function is not called. Below is my code -
In class AuthenticationViewController -
#class AuthenticationViewController;
#protocol ApplicationTiomeoutDelegate <NSObject>
-(void) addObserverForTimeout;
#end
And call this function using delegate -
[self.appTimeoutDelegate addObserverForApplicationTimeout];
And in AppDelegate, I have implemented this protocol like this -
#interface AppDelegate () <ApplicationTiomeoutDelegate>
#end
And then set delegate to self -
AuthenticationViewController *timeoutDelegate = [[AuthenticationViewController alloc] init];
[timeoutDelegate setAppTimeoutDelegate:self];
And implemented delegate function as well in AppDelegate, which is never called somehow -
-(void) addObserverForApplicationTimeout{
// this function is never called
}
I am not sure what is not correct here.
AppDelegate being a singleton need not have the ApplicationTiomeoutDelegate protocol invocation. You can directly invoke addObserverForTimeout
You create method in your appdelegate, you can directly call it wherever you want with instance of appdelegate.
For your question, check this below
Where are creating instance for Your delegate and where are calling your delegate form your viewcontroller, it is used to communicate between two class, it should have reference of protocol.
try this
Your viewcontroller.h
#protocol customDelegate;
#import <UIKit/UIKit.h>
#import "CustomTableViewCell.h"
#interface ViewController : UIViewController<UITableViewDelegate>
{
IBOutlet UITableView *mainTableView;
}
#property (nonatomic,strong) id <customDelegate> delegate;
#end
#protocol customDelegate <NSObject>
-(void)method;
#end
ViewController.m
- (void)viewDidLoad {
[self.delegate method];
}
Your app delegate
#interface AppDelegate () <customDelegate>
#end
Your didfinishlaunghing
viewController = [[ViewController alloc]initWithNibName:#"ViewController" bundle:nil];
viewController.delegate = self;
and implement method:
-(void)method{
NSLog(#"calling");
}
I've been following this example to help me build a delegate but unfortunately I've missed something so it is not working for me. How do I set up a simple delegate to communicate between two view controllers?
My code looks like this:
// HintsViewController.h
#import <UIKit/UIKit.h>
#protocol HintDelegateProtocol;
#interface HintsViewController : UIViewController
#property (weak, nonatomic) id<HintDelegateProtocol> hintDelegate;
-(IBAction)showFirstLetter:(id)sender
-(IBAction)showHint:(id)sender;
-(IBAction)showAnswer:(id)sender;
#end
#protocol HintDelegateProtocol <NSObject>
-(void)HintsViewController:(HintsViewController*)hintsViewController
showFirstLetter:(NSString*)firstLetter;
-(void)HintsViewController:(HintsViewController*)hintsViewController
showHint:(NSString*)hint;
-(void)HintsViewController:(HintsViewController*)hintsViewController
showAnswer:(NSString*)answer;
#end
//
// HintsViewController.m
#import "HintsViewController.h"
#implementation HintsViewController
#pragma mark -
#pragma mark IBActions
/* As per a suggestion below I changed the code here /*
- (IBAction)showHint:(id)sender
{
[self.hintDelegate HintsViewController:self showHint:#"Hint"];
}
- (IBAction)showFirstLetter:(id)sender
{
[self.hintDelegate HintsViewController:self showFirstLetter:#"FirstLetter"];
}
- (IBAction)showAnswer:(id)sender
{
[self.hintDelegate HintsViewController:self showAnswer:#"Answer"];
}
#end
And then in the a Controller class I have the following:
//
// GameLogicController.h
#import "HintsViewController.h"
#interface GameLogicController : NSObject < HintDelegateProtocol>
#end
And in the implementation I have the following:
// GameLogicController.m
-(void) nextRiddle
{
HintsViewController *hintsViewController = [[HintsViewController alloc] init];
hintsViewController.hintDelegate = self;
}
#pragma mark -
#pragma mark HintsFunctionality
-(void)HintsViewController:(HintsViewController*)hintsViewController
showFirstLetter:(NSString*)firstLetter
{
NSLog(#"Show First Letter called");
}
-(void)HintsViewController:(HintsViewController*)hintsViewController
showHint:(NSString*)hint
{
NSLog(#"show Hint called");
}
-(void)HintsViewController:(HintsViewController*)hintsViewController
showAnswer:(NSString*)answer
{
NSLog(#"Show answer called");
}
Using breakpoints I can see that the IBActions in the HintsViewController are being called, but putting a breakpoint in any of the delegate methods in the gameLogicController are never hit. So I have missed an important step in setting up the connection between the GameLogicController and the HintsViewController. Can anyone help me spot it?
Say you have two files: one is your ViewController, and other is your ConnectionManager Class.
Declare protocol and its methods in your ConnectionManager class, and define your protocol methods in the ViewController class. By setting the delegate of your ConnectionManager class in ViewController Class, you can call your Protocol method.
#protocol ConnManagerDelegate<NSObject>
- (void)didReceiveData:(NSDictionary *)data;
- (void)didFailWithError:(NSError*)error;
#end
#interface ConnectionManager : NSObject<NSURLConnectionDelegate>
#property(nonatomic,assign)id< ConnManagerDelegate > delegate;
And elseswhere in the same file .m, when your response comes just call
[Self.delegate didReceiveData:mDict];
In the ViewController file after you alloc init ConnectionManager class, set its delegate to self and define the protocol methods. It is these methods you will have your response from ConnectionManager class.
This is all Protocol Delegation pattern
I am implementing an library(.a), and I want to send notification count from library to app so they can show in their UI, notification count. I want them to implement the only method like,
-(void)updateCount:(int)count{
NSLog(#"count *d", count);
}
How can I send the count from my library continuously so they can use it in updateCount method to show.
I searched and come to know about call back functions. I have no idea how to implement them. Is there any other way to do this.
You have 3 options
Delegate
Notification
Block,also known callback
I think what you want is Delegate
Assume you have this file as lib
TestLib.h
#import <Foundation/Foundation.h>
#protocol TestLibDelegate<NSObject>
-(void)updateCount:(int)count;
#end
#interface TestLib : NSObject
#property(weak,nonatomic)id<TestLibDelegate> delegate;
-(void)startUpdatingCount;
#end
TestLib.m
#import "TestLib.h"
#implementation TestLib
-(void)startUpdatingCount{
int count = 0;//Create count
if ([self.delegate respondsToSelector:#selector(updateCount:)]) {
[self.delegate updateCount:count];
}
}
#end
Then in the class you want to use
#import "ViewController.h"
#import "TestLib.h"
#interface ViewController ()<TestLibDelegate>
#property (strong,nonatomic)TestLib * lib;
#end
#implementation ViewController
-(void)viewDidLoad{
self.lib = [[TestLib alloc] init];
self.lib.delegate = self;
[self.lib startUpdatingCount];
}
-(void)updateCount:(int)count{
NSLog(#"%d",count);
}
#end
I ultimately want to write an iOS app incorporating ALAssetsLibrary, but as a first step toward understanding delegation, I'm trying to pass a simple message between two view controllers. For some reason, I can't seem to get the message to pass. In particular, the delegate object (derpy) doesn't appear to exist (if(self.derpy) returns NO)).
I asked the same question on the Apple forums and was told that I should be using segues and setting properties / calling methods using self.child instead, but that seems strange. If I were to pass messages using the parent / child properties, would I still be able to create my views in Interface Builder? Once I have my two views set up, say inside a UINavigationController, I'm not sure how to actually "wire them up" so I can pass messages between them. Sorry if the question is overly broad.
Here's the controller I'm declaring the protocol in (called PickerViewController):
Interface:
#import <UIKit/UIKit.h>
#import <AssetsLibrary/AssetsLibrary.h>
#protocol DerpDelegate <NSObject>
#required
- (void) test;
#end
#interface PickerViewController : UIViewController
#property (nonatomic, assign) id<DerpDelegate> derpy;
#end
Implementation:
#import "PickerViewController.h"
#interface PickerViewController ()
#end
#implementation PickerViewController
- (void)viewDidLoad
{
[super viewDidLoad];
if (self.derpy) { // If the delegate object exists
[self.derpy test]; // send it this message
} else {
NSLog(#"Still not working."); // This always returns (i.e., self.derpy doesn't exist)
}
}
Delegate controller (MainViewController) interface:
#import <UIKit/UIKit.h>
#import "PickerViewController.h"
#interface MainViewController : UIViewController <DerpDelegate> // public promise to implement delegate methods
#property (strong, nonatomic) PickerViewController *picker;
- (void) test;
#end
And lastly, the delegate controller (MainViewController) implementation:
#import "MainViewController.h"
#import "PickerViewController.h"
#interface MainViewController ()
#end
#implementation MainViewController
// Here's that method I promised I'd implement
- (void) test{
NSLog(#"Test worked."); // This never gets called
}
- (void)viewDidLoad {
[super viewDidLoad];
self.picker.derpy = self;
//lazy instantiation
- (PickerViewController *) picker{
if(!_picker) _picker = [[PickerViewController alloc]init];
return _picker;
}
EDIT: Many thanks to rydgaze for pointing me in the right direction with self.picker.derpy = self, but for some reason, things still aren't working properly. Importantly, once that property has been set, if(self.picker.derpy) returns YES from MainViewController. But if(self.derpy) is still returning NO when called from inside the PickerViewController's viewDidLoad. How can the property exist and not exist at the same time?
You need to be sure that you're setting the delegate on the instance of the view controller that you put on screen. If you're using a navigation controller and segues to go between MainViewController and PickerViewController, then you should set the delegate in prepareForSegue:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
self.picker = (PickerViewController *)segue.destinationViewController;
self.picker.derpy = self;
}
You need to populate the delegate first.
Basically, your MainViewController shoudl at somepoint do a
picker.derpy = self;
Then when the delegate fires in PickerViewController, the callback will happen.
Edit:
A good practice is to do something like in PickerViewController
#property (nonatomic, assign) id<DerpDelegate > derpy;
and in your MainViewController indicate that you will implement the delegate
#interface MainViewController : UIViewController<DerpDelegate>
Eventually in your implementation of MainViewController
You will have something like
picker = [[PickerViewController alloc]init];
picker.derpy = self;
[picker doYourThing];
Once picker is all done, it may want to return results using the delegate.
i have created a delegate for my project the code of my main view is
VedantViewController.h
#protocol VedantDelegate;
#interface VedantViewController : UIViewController
{
id <VedantDelegate> delegate;
}
//some other outlets
#property(nonatomic, assign) id <VedantDelegate> delegate;
#protocol VedantDelegate <NSObject>
- (void)display:(NSString *)JSONResponse;
#end
VedantViewController.m
#synthesize delegate;
[delegate display:jsonResponse];
SecondViewController.h
#interface SecondViewController : UIViewController<VedantDelegate>
- (void)display:(NSString *)JSONResponse;
SecondViewController.m
- (void)display:(NSString *)string
{
}
but this code is not working properly
when i debug the code using breakpoints the code reaches the
[delegate display:abc];
but it does not calls display function in SecondViewController.m file
i think my code is right but some mistake that i can't recognize
let me explain you the flow of my project this could be the problem
by default the VedantViewController view is launched
after that when the show button is click it calls the SecondViewController view in the view these is list button that calls the function in VedantViewController this function then calls the delegate method that is [delegate display:jsonResponse];
Thanks in Advance,
Arun.
The view controller which is confirming with the protocol, should have this line in the viewDidLoad or anywhere you are making the object of that viewController
Add this line in SecondViewController.m
VedantViewControllerObject.delegate = self;
#protocol VedantDelegate;
#interface VedantViewController : UIViewController{
id<VedantDelegate> delegate;
}
//some other outlets
#property(nonatomic,assign) id<VedantDelegate> delegate;
#protocol VedantDelegate <NSObject>
-(void)displayAccounts:(NSString *)JSONResponse;
-(void)display:(NSString *)JSONResponse;
#end
and also set delegate to object of VedantViewControllerObject class as self in SecondViewController class and the object of VedantViewControllerObject class should be initialized and allocated.
vedantViewControllerObject.delegate = self;
In your VedantViewController.h file you declared method as below
-(void)displayAccounts:(NSString *)JSONResponse;
But you are calling it [delegate display:jsonResponse];
You just try to call
[delegate displayAccounts:jsonResponse];
And in SecondViewController.m
(void)displayAccounts:(NSString *)string{
}
There are some issues in your code:
set the delegate in second view controller
vedViewObject.delegate = self;
You added displayAccounts method in delegate and calling display method, that can cause issues. If that methods are not implemented in the delegate class.
Add if condition like: if(delegate)[delegate displayAccounts:jsonResponse];