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

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

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

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

你有3个选项

  1. 代表
  2. 通知
  3. 块,也称为callback

我想你想要的是代表

假设你有这个文件作为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