Pass Data between two view controllers using '

2020-07-24 03:20发布

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条回答
爷的心禁止访问
2楼-- · 2020-07-24 04:09

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
查看更多
登录 后发表回答