i am novice in Objective-c . i am learning objective-c . would you kindly let me know how this code work as well as would you kindly help to understand delegates work flow in objective-c
SampleProtocol.h
#import <Foundation/Foundation.h>
@protocol SampleProtocolDelegate <NSObject>
@required
- (void) processCompleted;
@end
@interface SampleProtocol : NSObject
{
id <SampleProtocolDelegate> _delegate;
}
@property (nonatomic,strong) id delegate;
-(void)startSampleProcess;
@end
after i added in SampleProtocol.m
below code
#import "SampleProtocol.h"
@implementation SampleProtocol
-(void)startSampleProcess{
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self.delegate
selector:@selector(processCompleted) userInfo:nil repeats:NO];
}
@end
Create an IBOutlet
for the label and name it as myLabel and update the code as follow to adopt SampleProtocolDelegate in ViewController.h
#import <UIKit/UIKit.h>
#import "SampleProtocol.h"
@interface ViewController : UIViewController<SampleProtocolDelegate>
{
IBOutlet UILabel *myLabel;
}
@end
and The Updated ViewController.m
file is as follows
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
SampleProtocol *sampleProtocol = [[SampleProtocol alloc]init];
sampleProtocol.delegate = self;
[myLabel setText:@"Processing..."];
[sampleProtocol startSampleProcess];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - Sample protocol delegate
-(void)processCompleted{
[myLabel setText:@"Process Completed"];
}
@end
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…