2012-10-22 37 views
0

我想创建一个库,我可以反复使用以加速我的开发,如果我添加到新项目希望。基本上我想建立一个抽象层。有人可以告诉我怎么做,为什么这部分代码:试图将代码抽象出一个库,但我的代码不工作,我不知道为什么

if ([self.delegate respondsToSelector:@selector(enableCamera)]) { 
     BOOL enabled; 
     enabled = [self.delegate enableCamera]; 
     if (enabled == YES) { 
      [self enableCameraMethod]; 

     } 

不会被调用?

HERES MY CODE BELOW:

library.h:

@protocol usesCamera <NSObject> 
@optional 
-(BOOL)enableCamera; 
@end 

@interface Library : NSObject 

@property (nonatomic, weak) id <usesCamera> delegate; 
-(void)enableCameraMethod; 
@end 

library.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 

回答

1

您是否在您的ViewController类中为您的myLibrary实例设置了委托。 你必须做这样的事情:

Library *myLibrary = [[Library alloc] init]; 
myLibrary.delegate = self; 

init的设置委托之前调用,因此可能无法工作,而不是定义在初始化函数的逻辑创建另一个方法调用此方法设置委托后。

相关问题