试图将代码抽象到库中,但我的代码不起作用,我不知道为什么

时间:2012-10-22 03:57:38

标签: iphone objective-c ios

我想创建一个我可以反复使用的库来加速我的开发,如果我愿意,可以添加到新项目中。基本上我想构建一个抽象层。有人可以告诉我我将如何做到这一点以及为什么这部分代码:

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

        }

没有被召唤?

以下是我的代码:

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 个答案:

答案 0 :(得分:1)

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

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

在设置委托之前调用init,因此它可能不起作用,而不是在init函数中定义逻辑,创建另一个方法并在设置委托后调用此方法。