Passing data between two view controllers via a protocol

不羁的心 提交于 2019-12-24 06:49:07

问题


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.


回答1:


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 { // 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.



来源:https://stackoverflow.com/questions/9741540/passing-data-between-two-view-controllers-via-a-protocol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!