Given the following code:
for (id object in anArray){
if ([object isKindOfClass:[ClassOne class]]){
ClassOne *myObj = [[ClassOne alloc] init];
}else if ([object isKindOfClass:[ClassTwo class]]){
ClassTwo *myObj = [[ClassTwo alloc] init];
}
myObj.property = TRUE;
}
the compiler will raise an error regarding myObj (undeclared identifier), which is somehow obvious (“what should I do if both conditions will be false?”). That means I have to define the object before the if-else block, but which type of object I have to use? If I use id there will be errors on myObj.property = TRUE;, if I use ClassOne or ClassTwo there will be some warnings regarding incompatible pointer assignment. Should I use some other way instead of the given code?
Thank you.
(note: the snippet was written without using syntax checking or testing it, so it may contains errors)
How about a protocol?
Then:
This is the cleanest and shortest solution I can think of. You won’t need to cast, instead you will harness the power of objective-c’s dynamic binding. You won’t have to add too many if-else statements. Instead you just make sure the object that comes in, conforms to your protocol.