我正在实现一个库 (.a),我想将通知计数从库发送到应用程序,以便它们可以在其 UI 中显示通知计数。我希望他们实现唯一的方法,例如,
-(void)updateCount:(int)count{
NSLog(@"count *d", count);
}
我怎样才能连续地从我的图书馆发送计数,以便他们可以在 updateCount 方法中使用它来显示。 我搜索并了解了回调函数。我不知道如何实现它们。有没有其他方法可以做到这一点。
最佳答案
你有3个选择
- 委托(delegate)
- 通知
- 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/