Skip to content

Instantly share code, notes, and snippets.

@0xced
Last active November 1, 2023 01:41
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xced/45daf79b62ad6a20be1c to your computer and use it in GitHub Desktop.
Save 0xced/45daf79b62ad6a20be1c to your computer and use it in GitHub Desktop.
Reverse engineered implementation of -[UIClassSwapper initWithCoder:]
@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
Copy link
Author

0xced commented May 7, 2015

If you drag & drop a custom object, i.e. the Object (NSObject) empty cube in a xib or storyboard, its UIOriginalClassName will be UICustomObject and thus will be initialized through init instead of initWithCoder: even if this object conforms to the NSCoding 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.

@getaaron
Copy link

@0xced Thanks a ton for posting this. It was very helpful.

@mikayelaghasyan
Copy link

@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