Created
November 21, 2015 23:19
-
-
Save dodikk/2cbcfb1462a21dfe4a0c to your computer and use it in GitHub Desktop.
Safe Cast templates for Objective-C
This file contains 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
#ifndef __JFF_CAST_FUNCTIONS_H__ | |
#define __JFF_CAST_FUNCTIONS_H__ | |
#import <Foundation/Foundation.h> | |
#pragma mark - | |
#pragma mark NSObject casts | |
template < class DESTINATION > | |
DESTINATION* objc_kind_of_cast( id nsObject ) | |
{ | |
Class destination_class_ = [ DESTINATION class ]; | |
if ( ![ nsObject isKindOfClass: destination_class_ ] ) | |
{ | |
NSLog( @"[!!!ERROR!!!] objc_kind_of_cast class mismatch. Expected : %@. Received : %@", destination_class_, [ nsObject class ] ); | |
return nil; | |
} | |
return (DESTINATION*)nsObject; | |
} | |
template < class DESTINATION > | |
DESTINATION* objc_member_of_cast( id nsObject ) | |
{ | |
Class destination_class_ = [ DESTINATION class ]; | |
if ( ![ nsObject isMemberOfClass: destination_class_ ] ) | |
{ | |
NSLog( @"[!!!ERROR!!!] objc_member_of_cast class mismatch. Expected : %@. Received : %@", destination_class_, [ nsObject class ] ); | |
return nil; | |
} | |
return (DESTINATION*)nsObject; | |
} | |
#pragma mark - | |
#pragma mark dynamic cast | |
extern BOOL class_srcIsSuperclassOfDest( Class src, Class dest ); | |
extern BOOL class_isClassesInSameHierarchy( Class src, Class dest ); | |
template < class DESTINATION > | |
DESTINATION* objc_dynamic_cast( id nsObject ) | |
{ | |
return objc_kind_of_cast<DESTINATION>( nsObject ); | |
} | |
template < class DESTINATION > | |
DESTINATION* objc_reinterpret_cast( id nsObject ) | |
{ | |
return (DESTINATION*)nsObject; | |
} | |
#endif //__JFF_CAST_FUNCTIONS_H__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment