客观的c代表理解

时间:2012-05-23 17:53:02

标签: objective-c

我有一个ApiClient类,它使用NSURLConnection从服务器获取一些数据并将其发送回其委托

我有另一个名为Fetcher.h的类,它调用ApiClient上的一些函数并在其中实现委托方法。

我有第三个类(View Controller)调用Fetcher.h executeCall()并触发整个过程。

    Fetcher *fetcher = [[Fetcher alloc] init];
    [fetcher getData];

如果我直接在View控制器中调用ApiClient代码,它可以正常工作。为什么它不会从Fetcher课程中发挥作用?我做错了什么?

在Fetcher getData中我有这段代码

APIClient* client = [APIClient sharedInstance];
[client setDelegate:self];
[client getData];

提前致谢。

2 个答案:

答案 0 :(得分:0)

试试这个......

@protocol APIClientProtocol <NSObject>
@optional
- (void) handleMessage;
@end

@interface APIClient : NSObject
@property (readwrite, nonatomic, strong) id<APIClientProtocol> delegate;
@end

@implementation APIClient
@synthesize delegate;

- (void) someAPIClientWork 
{

   // Do some client work here

   if ( [self.delegate respondsToSelector:@selector(handleMessage)] )
      [self.delegate performSelector:@selector(handleMessage)];
}

@end

.h of Fetcher

@interface Fetcher : NSObject <APIClientProtocol>
@end

.m of Fetcher

@implementation Fetcher

- (void) someInit 
{
   APIClient *client = [APIClient sharedInstance];
   client.delegate = self;
}

- (void) handleMessage 
{

   // Something in APIClient was called
}

@end

答案 1 :(得分:0)

由于您没有将您在viewcontroller中创建的Fetcher对象分配给任何属性或任何内容,因此可能会在您分配它的任何方法的最后发布它。尝试添加此到你的viewcontroller:

·H

@interface ViewController

@property (strong, nonatomic) Fetcher *myFetcher; //Add this line in your view controller's interface
...

的.m

@implementation ViewController

@synthesize myFetcher;
...
Fetcher *fetcher = [[Fetcher alloc] init];
[fetcher getData];
self.myFetcher = fetcher;//Add this line in your code as well