gpt4 book ai didi

iphone - 第一次使用协议(protocol) - Objective-C

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:10:37 26 4
gpt4 key购买 nike

这是我第一次在 Objective-C 中使用协议(protocol),我遇到了麻烦:这是我得到的:

我有一个 ReportsReceiver.h:

@protocol ReportsReceiver


-(void)receiveData:(NSArray *)theData;

@end

我有一个 MyController.h:

@interface MyController : UIViewController<ReportsReceiver,UITableViewDelegate,UITableViewDataSource> {

}
@end

我有一个带有实现方法的 MyController.m:

- (void)receiveData:(NSArray *)theData {
NSLog(@"received some data!");
}

然后我有一个带有声明的类 AllUtilities.m:

Protocol *receiverProtocol;

AllUtilities.m 还包含一个初始化协议(protocol)的方法:

- (void)initProtocol {
receiverProtocol = @protocol(ReportsReceiver);

}

然后我稍后在 AllUtilities.m 中调用:

[receiverProtocol receiveData:anArray];

导致应用程序崩溃并出现以下错误:

2011-01-07 11:46:27.503 TestGA[91156:207] *** NSInvocation: warning: object 0x9c28c of class 'Protocol' does not implement methodSignatureForSelector: -- trouble ahead
2011-01-07 11:46:27.504 TestGA[91156:207] *** NSInvocation: warning: object 0x9c28c of class 'Protocol' does not implement doesNotRecognizeSelector: -- abort

我该如何解决这个问题?谢谢!!

最佳答案

您应该阅读 Objective-C guide 中有关协议(protocol)的部分再一次 :) 我认为你并不真正理解协议(protocol)是如何工作的。这就是你想要的:

// DataProducer.h
@protocol DataConsumer
- (void) handleData: (NSArray*) data;
@end

@interface DataProducer
@end

// DataProducer.m
@implementation DataProducer

- (void) generateDataAndPassTo: (id <DataConsumer>) consumer
{
NSArray *data = …;
[consumer handleData:data];
}

// SomeController.h
#import "DataProducer.h"

@interface SomeController <DataConsumer>
@end

// SomeController.m
@implementation SomeController

- (void) requestData
{
// The producer is of type DataProducer.
// Where you get it is irrelevant here.
[producer generateDataAndPassTo:self];
}

- (void) handleData: (NSArray*) data
{
NSLog(@"Got data.");
}

@end

关于iphone - 第一次使用协议(protocol) - Objective-C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4627973/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com