Pass Data between two view controllers using 'Delegation' : Objective-C

妖精的绣舞 提交于 2020-01-01 17:09:37

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/30662032/pass-data-between-two-view-controllers-using-delegation-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!