Created
June 15, 2018 06:35
-
-
Save acalism/39ce104cfc69ec0a580f2873a97bf4a2 to your computer and use it in GitHub Desktop.
Implementation and Inheritance of objc lightweight generics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Header File | |
NS_ASSUME_NONNULL_BEGIN | |
// No asterisk after DataType | |
@interface BaseCell<DataType> : UICollectionViewCell | |
- (DataType)data; | |
- (void)bindData:(DataType)data; | |
@end | |
// Specify generic type in subclass | |
@interface MyCell: BaseCell | |
- (void)bindData:(__kindof UIView *)data; | |
@end | |
NS_ASSUME_NONNULL_END | |
// Implementation File | |
// Can not use generic type, use `id` instead. | |
@implementation BaseCell | |
- (id)data { | |
return @"no data"; | |
} | |
- (void)bindData:(id)data { | |
[NSObject doesNotRecognizeSelector:_cmd]; | |
} | |
@end | |
@implementation MyCell | |
- (void)bindData:(__kindof UIView *)data { | |
NSLog(@"bindData"); | |
} | |
@end | |
// Another file | |
MyCell *m = [MyCell new]; | |
[m bindData:[UIView new]]; | |
[m bindData:@""]; // Warning: Incompatible pointer types sending |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Further more, generic type can have base class or protocol conforming constraints.
Refer to http://drekka.ghost.io/objective-c-generics/ and https://miqu.me/blog/2015/06/09/adopting-objectivec-generics/
According to Apple's documentation: