我想创建一个可以反复重用的库,以加快我的开发速度,如果我愿意,可以添加到新项目中。基本上我想建立一个抽象层。有人可以告诉我如何做到这一点以及为什么这部分代码:
if ([self.delegate respondsToSelector:@selector(enableCamera)]) {
BOOL enabled;
enabled = [self.delegate enableCamera];
if (enabled == YES) {
[self enableCameraMethod];
}
不叫?
下面是我的代码:
图书馆.h:
@protocol usesCamera <NSObject>
@optional
-(BOOL)enableCamera;
@end
@interface Library : NSObject
@property (nonatomic, weak) id <usesCamera> delegate;
-(void)enableCameraMethod;
@end
图书馆.m
#import "Library.h"
@implementation Library
- (id) init
{
if (self = [super init]) {
if ([self.delegate respondsToSelector:@selector(enableCamera)]) {
BOOL enabled;
enabled = [self.delegate enableCamera];
if (enabled == YES) {
[self enableCameraMethod];
}
}
return (self);
}
}
-(void)enableCameraMethod {
NSLog(@"Implement my camera method here");
}
@end
UIViewController.h
#import <UIKit/UIKit.h>
#import "Library.h"
@interface ViewController : UIViewController <usesCamera>
@end
UIViewController.m
#import "ViewController.h"
#import "Library.h"
@interface ViewController ()
@property (nonatomic, strong) UIViewController *myVC;
@end
@implementation ViewController
-(BOOL)enableCamera {
return YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
Library *myLibrary = [[Library alloc] init];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end