object_setClass to bigger class
I am changing the class of some objects using
object_setClass(id object, Class cls). I am changing the class to a subclass of the original class. Then I set some properties that are only defined on the subclass, and things seem to work fine.
I was a bit surprised that this worked, because
object_setClass, as far as I understand, doesn’t reallocate the object, it only changes the
isa pointer. If the subclass instances are considerably larger (meaning having many more ivars) than the original class instances, I don’t see how the object can work as expected.
Does this work only because there is a lot of buffer memory between objects in memory (due to alignment etc)?
Is this robust, or could it crash under some circumstances?
- How can I dynamically create a selector at runtime with Objective-C?
- iOS UITableViewCells rows recycled and tag not working
- Swift-Access UILabels in dynamic cells in UITableView
- cast NSManagedObject to class -> Swift dynamic cast failed
- How SHOULD you make (and use) static libraries on the iPhone
- A dynamic method name (Objective-C)
2 Solutions Collect From Internet About “object_setClass to bigger class”
It could crash. As can be seen in the source code of the runtime here, it really just swaps the
If you really want to swap the
isa to an
isa of a subclass with more ivars, you should use
class_createInstance with nonzero
Instead of using a larger subclass, use
objc_getAssociatedObject to attach dynamically additional objects to your existing fixed-size object.
- Setting the active executable in Xcode
- How to take Picture Programmatically in iphone App using device camera?
- How to programmatically differentiate between iphone 4 and iphone 4S?
- Firebase API is not sending push notifications when using the API
- AVAudioPlayer not playing audio in Swift
- Subclassing a UIView subclass loaded from a nib
- Single quotes around IBAction
- New @convention(c) in Swift 2: How can I use it?
- Check whether time falls between two time iOS
- Is it possible to change UITabBarItem badge color
- UITableViewCellDeleteConfirmationControl issue
- Appium on real iOS devices
- how to get Distance of Object from iPhone camera using image Exif meta data?
- How to filter multiple fields in UITableView in swift
- Display images in a UICollectionView – how to achieve fixed vertical spacing between images?