Last active
November 1, 2023 01:41
-
-
Save 0xced/45daf79b62ad6a20be1c to your computer and use it in GitHub Desktop.
Reverse engineered implementation of -[UIClassSwapper initWithCoder:]
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
@implementation UIClassSwapper | |
- (instancetype) initWithCoder:(UINibDecoder *)decoder | |
{ | |
NSString *className = [decoder decodeObjectForKey:@"UIClassName"]; | |
NSString *originalClassName = [decoder decodeObjectForKey:@"UIOriginalClassName"]; | |
Class class = NSClassFromString(className); | |
Class originalClass = NSClassFromString(originalClassName); | |
if (!class) { | |
NSLog(@"Unknown class %@ in Interface Builder file.\n", className); | |
} | |
id object = [(class ?: originalClass) alloc]; | |
[decoder replaceObject:self withObject:object]; | |
if (originalClass != [UICustomObject class]) { | |
self = [object initWithCoder:decoder]; | |
} | |
else { | |
self = [object init]; | |
} | |
return [self autorelease]; | |
} | |
@end |
@0xced Thanks a ton for posting this. It was very helpful.
@0xced Do you know of any way to make the custom object's UIOriginalClassName
something other than UICustomObject
and thus, have it initialized with initWithCoder:
initializer?
Thanks beforehand!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you drag & drop a custom object, i.e. the Object (NSObject) empty cube in a xib or storyboard, its
UIOriginalClassName
will beUICustomObject
and thus will be initialized throughinit
instead ofinitWithCoder:
even if this object conforms to theNSCoding
protocol.Contrary to what you might expect, changing the custom class of a custom object in the IB inspector won’t affect how it’s initialized. If it was created as a custom object, it will always be initialized with the
init
method, no matter what its custom class is.