Skip to content

Instantly share code, notes, and snippets.

@steipete
Last active April 28, 2020 15:08
Show Gist options
  • Save steipete/d6ba2d5a5cb939a2675ee20216fb45c8 to your computer and use it in GitHub Desktop.
Save steipete/d6ba2d5a5cb939a2675ee20216fb45c8 to your computer and use it in GitHub Desktop.
Override copy and mutableCopy on Objective-C collection classes to pass along both the collection type and the generic info. This is a header-only "library". MIT licensed. Craving for more? foreach: https://gist.github.com/steipete/7e3c69b985165dc23c5ec169b857ff42 even more: https://pspdfkit.com/blog/2016/swifty-objective-c/ - ships in https://p…
//
// PSPDFGenerics.h
// PSPDFFoundation
//
// PSPDFKit is the leading cross-platform solution for integrating PDFs into your apps: https://pspdfkit.com.
// Try it today using our free PDF Viewer app: https://pdfviewer.io/
//
// This file is MIT licensed.
/**
This file overrides the NSObject declaration of copy with specialized ones that retain the generic type.
This is pure compiler sugar and will create additional warnings for type mismatches.
@note id-casted objects will create a warning when copy is called on them as there are multiple
declarations available. Either cast to specific type or to NSObject to work around this.
*/
@interface NSArray <ElementType> (PSPDFSafeCopy)
/// Same as `copy` but retains the generic type.
- (NSArray <ElementType> *)copy;
/// Same as `mutableCopy` but retains the generic type.
- (NSMutableArray <ElementType> *)mutableCopy;
@end
@interface NSSet <ElementType> (PSPDFSafeCopy)
/// Same as `copy` but retains the generic type.
- (NSSet <ElementType> *)copy;
/// Same as `mutableCopy` but retains the generic type.
- (NSMutableSet <ElementType> *)mutableCopy;
@end
@interface NSDictionary <KeyType, ValueType> (PSPDFSafeCopy)
/// Same as `copy` but retains the generic type.
- (NSDictionary <KeyType, ValueType> *)copy;
/// Same as `mutableCopy` but retains the generic type.
- (NSMutableDictionary <KeyType, ValueType> *)mutableCopy;
@end
@interface NSOrderedSet <ElementType> (PSPDFSafeCopy)
/// Same as `copy` but retains the generic type.
- (NSOrderedSet <ElementType> *)copy;
/// Same as `mutableCopy` but retains the generic type.
- (NSMutableOrderedSet <ElementType> *)mutableCopy;
@end
@interface NSHashTable <ElementType> (PSPDFSafeCopy)
/// Same as `copy` but retains the generic type.
- (NSHashTable <ElementType> *)copy;
@end
@interface NSMapTable <KeyType, ValueType> (PSPDFSafeCopy)
/// Same as `copy` but retains the generic type.
- (NSMapTable <KeyType, ValueType> *)copy;
@end
@steipete
Copy link
Author

Unfortunately, yes.

@revolter
Copy link

Btw, thanks a lot for this! I had someMutableArray = [simpleArray copy] which could have led to a runtime crash 😨

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment