ios - 使用 'Delegation' : Objective-C 在两个 View Controller 之间传递数据

标签 ios objective-c design-patterns callback delegates

我正在实现一个库 (.a),我想将通知计数从库发送到应用程序,以便它们可以在其 UI 中显示通知计数。我希望他们实现唯一的方法,例如,

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

我怎样才能连续地从我的图书馆发送计数,以便他们可以在 updateCount 方法中使用它来显示。 我搜索并了解了回调函数。我不知道如何实现它们。有没有其他方法可以做到这一点。

最佳答案

你有3个选择

  1. 委托(delegate)
  2. 通知
  3. block ,也称为回调

我觉得你想要的是Delegate

假设你有这个文件作为 lib

测试库.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

测试库.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

关于ios - 使用 'Delegation' : Objective-C 在两个 View Controller 之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30662032/

相关文章:

ios - 如何使光标的高度与 UITextField 中文本的高度相同?

python - 多种DAL设计模式

objective-c - 从 XIB 加载 viewForSectionHeader 时遇到问题

ios - 应用程序仅在 iPhone7 上崩溃 : Fatal Exception: CALayerInvalidGeometry CALayer position contains NaN: [nan nan]

ios - 使用 scrollview 截取 ViewController 的屏幕截图

Objective-C - Cocoa 类簇的有效子类化

Android 数据访问设计模式 : Content provider vs repository

html - 如何将 CSS 定位与 CSS 样式分开?

ios - 停用 unicode 字符的语言环境

ios - 为什么多次调用 UITableView numberOfRowsInSection?