Reputation: 1351
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.
Upvotes: 1
Views: 692
Reputation: 14068
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.
Upvotes: 2