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

Sha*_*ore 2 delegates design-patterns objective-c callback ios

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

-(void)updateCount:(int)count{
    NSLog(@"count *d", count);
}
Run Code Online (Sandbox Code Playgroud)

如何从库中连续发送计数,以便他们可以在updateCount方法中使用它来显示.我搜索并了解回叫功能.我不知道如何实现它们.有没有其他方法可以做到这一点.

Leo*_*Leo 7

你有3个选择

  1. 代表
  2. 通知
  3. 块,也称回调

我想你想要的是代表

假设您将此文件作为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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

然后在你想要使用的课程中

#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
Run Code Online (Sandbox Code Playgroud)