需要为API调用开发自定义委托

时间:2015-06-29 08:45:03

标签: ios delegates nsurlconnection appdelegate

我想开发自定义连接类,通过它我可以使用它进行API调用。我不想使用任何第三方apis,如afhttprequest或asihttp。

我想发展自己这种代表。我搜索了很多东西,但我在CustomDelegates中没有太多想法。

1 个答案:

答案 0 :(得分:2)

我写了一个自定义委托的例子。

  1. 从ViewController.m我们调用带有两个数字的方法来添加另一个类(加法类)
  2. 添加类将添加这两个数字并调用委托方法,以便我们可以使用自定义委托在ViewController中获得该两个数字的答案。
  3. 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
    

    我希望它能帮到你