I have a small function which I want to rewrite, so that function is valid for every class. At the moment I have 10 of the same functions which all work same but every function is for another class. I know, that I have to do it with reflections, but I am not so sure how to do it. I already read this link: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html
The functions I am talking about are:
-(NSCountedSet *)MissionGetReferecedNested:(id)modelObject
{
setOfObjects = [[NSCountedSet alloc]initWithArray:modelObject.MissionSectionList];
return setOfObjects;
}
-(NSCountedSet *)MissionGetSectionReferecedNested:(id)modelObject
{
setOfObjects = [[NSCountedSet alloc]initWithArray:modelObject.DamageAccountList];
return setOfObjects;
}
MissionSectionList and DamageAccountList are both NSMutableArrays from two different classes. Is it possible to see if a class consists a NSMutableArray and if yes then it should call the .... modelObject.MyMutableArray?
You can use reflection like this:
But a more common technique among cocoa programmers would be:
Where you would accept any object which confirms to the protocol
MyCustomProtocol
. The protocol is defined in a header files somewhere, using:And then in each of your classes, declare it as implementing the protocol:
And add a method implementation:
Using protocols is a bit more code, but it's the "right" way to go. It allows you to add support for new classes, without any change to your
MissiongGet...
method.More info about protocols: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProtocols.html