使用'委托'在两个视图控制器之间传递数据。 :Objective-C

时间:2015-06-05 08:40:52

标签: ios objective-c design-patterns callback delegates

我正在实现一个库(.a),我想从库向app发送通知计数,以便他们可以在他们的UI中显示通知计数。我希望他们实现唯一的方法,如

-(void)updateCount:(int)count{
    NSLog(@"count *d", count);
}

如何连续从我的库中发送计数,以便他们可以在updateCount方法中使用它来显示。 我搜索并了解回叫功能。我不知道如何实现它们。还有其他办法吗?

1 个答案:

答案 0 :(得分:7)

您有3个选项

  1. 代表
  2. 通知
  3. Block,也称为回调
  4. 我认为你想要的是代表

    假设您将此文件设为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
    

    然后在你要使用的课程中

    #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