Question

I have two pices of code:

for(Class<ContactV2Storage> tmpClass in config->ctxStorageClasses){
    id<ContactV2Storage> stor = [[[tmpClass alloc] init] autorelease];
}

and

for(Class tmpClass in config->ctxStorageClasses){
    id<ContactV2Storage> stor = [[[tmpClass alloc] init] autorelease];
}

Both works this same, but while using first version (which I believe is better) compiler gives me a warning:

Class method '+alloc' not found (return type defaults to 'id')

I'm curious why this is happening?

Was it helpful?

Solution

The Class type represents an Objective-C class (which is a C struct). See the runtime docs here.

Only definitions of a Class can conform to a protocol (you can check with class_conformsToProtocol or NSObject's conformsToProtocol:). So your first piece of code is incorrect to use Class<ContactV2Storage>.

The second piece is mostly correct, but a safer way to do it would be:

for(Class tmpClass in config->ctxStorageClasses) {
    if([tmpClass conformsToProtocol:@protocol(ContactV2Storage)]) {
        id<ContactV2Storage> stor = [[[tmpClass alloc] init] autorelease];
        // do stuffs
    }
}

This way you are sure that the class you are instantiating adheres to the protocol and can safely receive any messages you send. If any methods in the protocol are optional, you should also check that the instantiated object (in this case, stor) responds to them before calling them, otherwise the application will crash.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top