objective-ciosuiviewcontrollerobjective-c-protocol

Is there a way to only allow UIViewControllers to adhere to a protocol?


Is there any way to do something like this (below doesn't work):

@protocol ElementPicker <UIViewController>

- (id)initWithFile:(NSFileWrapper *)file andInfo:(NSString *)info;

@property (nonatomic, weak) NSObject<ElementPickerDelegate> *delegate;
@end

So that objects that implement "ElementPicker" must inherit from UIViewController?


Solution

  • No. Protocols can only extend other protocols. The closest you can do is define a variable, property, or parameter as being a UIViewController that also adheres to the ElementPicker protocol. Something like this:

    - (void)someMethod:(UIViewController<ElementPicker> *)controller {
    }
    

    Side note - it is common to define delegates as id, not NSObject. Such as:

    @property (nonatomic, weak) id<ElementPickerDelegate> delegate;