通过协议在两个视图控制器之间传递数据 [英] Passing data between two view controllers via a protocol
问题描述
如何声明和实现一个返回视图属性的协议?例如.我有一个名为 mainView 的视图,我希望它能够在另一个视图(例如 customView)请求它时返回一个数组.我正在做的是在 mainView 实现文件中声明一个协议(带有 returnTheArray 函数)并将 customView 设置为采用该协议,但我在这一点上被卡住了.我该怎么做才能使其正常工作?或者有更有效/简单/正确的方法来做到这一点?谢谢.
How to declare and implement a protocol that will return a view's property? E.g. I have an view called mainView and I want it to be able to return an array when another view, customView for example, asks for it. What I'm doing is that I'm declaring a protocol in the mainView implementation file (with a returnTheArray function) and set the customView to adopt this protocol, but I'm stuck at this point. What should I do to get this working correctly? Or there is a more effective/easy/correct way to do this? Thanks.
推荐答案
协议本身只是函数/方法名称、参数和返回值的声明.因为一个协议对我来说只有在它由多个类实现时才合理,我个人更喜欢在单独的头协议名称.h 中声明它.
The protocol as such is only a declaration of the function/method name, parameters and return values. As a protocol to me is only reasonalbe when it is fulfilled by a number of classes, I personally prefer to declare it in an individual header protocolName.h.
每个符合协议的类都需要实现方法.我的理解就是这么简单.
Every class that conforms to the protocol needs to implement the method(s). For my undertanding it is as simple as that.
AClass.h
@itnerface AClass:NSObject {//一些属性}//@property 语句@结束
@itnerface AClass:NSObject { // some properties } // @property statements @end
AClass.m
#include "BClass.h"
@implementation AClass
//@synthesize statements;
- (void) aFunctionFetchingTheArray {
BClass *bClass = [[BClass alloc] initWithSomething:kParameter];
NSArray *anArray = [bClass returnTheArray];
//Do something with it
}
@end
MyProtocol.h
@protocol MyProtocol
- (NSArray *) returnTheArray;
@end
BClass.h
#include "MyProtocol.h"
@interface BClass <MyProtocol> {
// some properties in interface
}
// some @property
// some methods
@end
BClass.m
#include "BClass.h" //No need to include MyProtocol.h here too, in this case
- (NSArray *) returnTheArray {
return [NSArray arrayWithObjects:@"A", [NSNumber numberWithtInt:1], [UIColor clearColor], somethingElse, evenMore, nil];
}
// more methods
@end
如果我遗漏或拼错了重要的东西,请更正.
Please correct my if I missed or misspelled something of importance.
这篇关于通过协议在两个视图控制器之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!