Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObjC: is there such a thing as a "class protocol"?

Tags:

objective-c

For object instances we can have their class declare some protocol conformance as in:

@protocol P <NSObject>
- (void) someMethod ;
@end

@interface C : NSObject <P>
@end

@implementation C
- (void) someMethod {

}
@end

But what about classes?

I find myself in this situation:

...
Class c = [self modelClass:kind] ;
if (c) {
    model = [c performSelector: @selector(decode:) 
                    withObject: [SExpIO read: [fm contentsAtPath:target]]] ;
}

and I wish there were a way for me to declare that there is such a thing as protocols for class methods.

In the above example, all classes that c can be a class-instance (Hmmm??) of, declare

+ (id) decode: (SExp *) root ;

Is there a way that I could transform the above into:

if (c) {
    model = [c decode: [SExpIO read: [fm contentsAtPath:target]]]
}

by using a suitable "class protocol" declaration?

like image 393
verec Avatar asked Feb 22 '12 00:02

verec


People also ask

What is a protocol OBJC?

Advertisements. Objective-C allows you to define protocols, which declare the methods expected to be used for a particular situation. Protocols are implemented in the classes conforming to the protocol.

What's the difference between a protocol and a class in Swift?

You can create objects from classes, whereas protocols are just type definitions. Try to think of protocols as being abstract definitions, whereas classes and structs are real things you can create.

Can a struct conform to a protocol?

Structs do not inherit from protocols, they conform to protocols.

What is protocol in iOS?

In iOS development, a protocol is a set of methods and properties that encapsulates a unit of functionality. The protocol doesn't actually contain any of the implementation for these things; it merely defines the required elements.


1 Answers

A protocol is just a list of method declarations. They can be class methods or instance methods. Example:

@protocol MyProtocol

+ (id) aClassMethod;
+ (void) someOtherClassMethod;
- (void) someInstanceMethod;

@end
like image 135
NSResponder Avatar answered Oct 21 '22 00:10

NSResponder