使用'委托'在两个视图控制器之间传递数据:Objective-C [英] Pass Data between two view controllers using 'Delegation' : Objective-C

查看:151
本文介绍了使用'委托'在两个视图控制器之间传递数据:Objective-C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如何连续从我的图库发送计数, updateCount方法显示。
我搜索并了解回调函数。我不知道如何实现它们。

解决方案

您有3个选项


  1. 委托

  2. 通知

  3. 阻止,也称为回叫

我想你想要的是Delegate



假设你有这个文件为lib

TestLib.h

  #import< Foundation / Foundation.h> 
@protocol TestLibDelegate< NSObject>
- (void)updateCount:(int)count;
@end

@interface TestLib:NSObject
@property(weak,nonatomic)id< TestLibDelegate>代表;
- (void)startUpdatingCount;
@end

TestLib.m

  #importTestLib.h

@implementation TestLib
- (void)startUpdatingCount {
int count = 0; / create count
if([self.delegate respondingToSelector:@selector(updateCount :)]){
[self.delegate updateCount:count];
}
}
@end

想要使用

  #importViewController.h
#importTestLib.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


I am implementing an library(.a), and I want to send notification count from library to app so they can show in their UI, notification count. I want them to implement the only method like,

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

How can I send the count from my library continuously so they can use it in updateCount method to show. I searched and come to know about call back functions. I have no idea how to implement them. Is there any other way to do this.

解决方案

You have 3 options

  1. Delegate
  2. Notification
  3. Block,also known callback

I think what you want is Delegate

Assume you have this file as 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

Then in the class you want to use

#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

这篇关于使用'委托'在两个视图控制器之间传递数据:Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆