2015-06-05 107 views
2

我正在实现一个库(.a),并且我想从库发送通知计数到应用程序,以便它们可以在其UI中显示通知计数。我希望他们能够实现的唯一方法类似,使用'Delegation'在两个视图控制器之间传递数据:Objective-C

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

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

+0

类你看了关于[代表团和通知(HTTPS:/ /developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/Delegation.html#//apple_ref/doc/uid/TP40008195-CH14-SW4)或[使用协议](https:// developer.apple .COM /库/ IOS /文档/可可/概念/ ProgrammingWithObjectiveC/WorkingwithProtocols/WorkingwithProtocols.html#// apple_ref/DOC/UID/TP40011210-CH11)? – Mats

回答

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 

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 
+0

它的工作原理。谢谢@Leo。 –

相关问题