object_setClass to bigger class - objective-c

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?

It could crash. As can be seen in the source code of the runtime here, it really just swaps the isa pointer.
If you really want to swap the isa to an isa of a subclass with more ivars, you should use class_createInstance with nonzero extraBytes.

Instead of using a larger subclass, use objc_setAssociatedObject and objc_getAssociatedObject to attach dynamically additional objects to your existing fixed-size object.

Related

Do Objective-C objects get their own copies of instance methods?

I'm new to Objective-C and was wondering if anyone could provide any information to clarify this for me. My (possibly wrong) understanding of object instantiation in other languages is that the object will get it's own copies of instance variables as well as instance methods, but I'm noticing that all the literature I've read thus far about Objective-C seems to indicate that the object only gets copies of instance variables, and that even when calling an instance method, program control reverts back to the original method defined inside the class itself. For example, this page from Apple's developer site shows program flow diagrams that suggest this:
https://developer.apple.com/library/mac/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/WorkingwithObjects/WorkingwithObjects.html#//apple_ref/doc/uid/TP40011210-CH4-SW1
Also in Kochan's "Programming in Objective-C", 6th ed., pg. 41, referring to an example fraction class and object, the author states that:
"The first message sends the setNumerator: message to myFraction...control is then sent to the setNumerator: method you defined for your Fraction class...Objective-C...knows that it's the method from this class to use because it knows that myFraction is an object from the Fraction class"
On pg. 42, he continues:
"When you allocate a new object...enough space is reserved in memory to store the object's data, which includes space for its instance variables, plus a little more..."
All of this would seem to indicate to me that there is only ever one copy of any method, the original method defined within the class, and when calling an instance method, Objective-C simply passes control to that original copy and temporarily "wires it" to the called object's instance variables. I know I may not be using the right terminology, but is this correct? It seems logical as creating multiple copies of the same methods would be a waste of memory, but this is causing me to rethink my entire understanding of object instantiation. Any input would be greatly appreciated! Thank you.
Your reasoning is correct. The instance methods are shared by all instances of a class. The reason is, as you suspect, that doing it the other way would be a massive waste of memory.
The temporary wiring you speak of is that each method has an additional hidden parameter passed to it: a pointer to the calling object. Since that gives the method access to the calling object, then it can easily access all of the necessary instance variables and all is well. Note that any static variable exists in only a single instance as well and if you are not aware of that, unexpected things can happen. However, regular local variables are not shared and are recreated for each call of a method.
Apple's documention on the topic is very good so have a look for more info.
Just think of a method as a set of instructions. There is no reason to have a copy of the same method for each object. I think you may be mistaken about other languages as well. Methods are associated with the class, not individual objects.
Yes, your thinking is more or less right (although it's simpler than that: behind the scenes in most such languages methods don't need to be "wired" to anything, they just take an extra parameter for self and insert struct lookups before references to instance variables).
What might be confusing you is that not all languages work this way, in their implementations and semantically. Object-oriented languages are (very roughly) divided into two camps: class-based, like Objective-C; and prototype-based, like Javascript. In the second camp of languages, a method or procedure really is an object in its own right and can often be assigned directly to an object's instance variables as well - there are no classes to lookup methods from, only objects and other objects, all with the same first-class status (this is an oversimplification, good languages still allow for sharing and efficiency).

How does objective-c handle method resolution at run-time?

I've read here recently that an objective-c object is stored on the heap as a struct. The struct contains the objects iVars, inherited iVars, and the isa pointer.
I'm trying to figure out when I send a message to this object, how does the run-time figure out the code to run?
I know there is a class object for each class. Is this also stored on the heap?
I think the way it works is that the run-time gets the isa pointer from the struct, uses this to call the message on the class object. Is this correct?
In short, every Objective-C instance has a pointer to its class. The class contains an inventory of metadata that includes all the methods that the class implements. When a message is sent to an object -- when a method is called -- the runtime uses the pointer to the class to lookup the method by name and call it, if it can be found. If it isn't found, the runtime looks to the superclass (which is a part of each class's metadata) on up the inheritance chain to NSObject. If the method ultimately can't be found, the runtime goes through a series of last ditch efforts to see if their is an alternative handler and eventually raises an exception, if not.
If you want more detail than that, I wrote up a multipart tour of exactly how Objective-C method dispatch works. It is slightly out of date -- doesn't deal with ARC, tagged pointers or blocks-as-IMP -- but still fully applicable.
Yes, classes are stored in the heap, but generally not in malloc()d memory. Classes are generally loaded as read-only, shared, memory. That is, there will be only one copy of the NSString class in memory for all applications running on the system. You can dynamically create classes on the fly and these will be in the regular heap, but it is atypical.

Objective-c: Reference to ivar persistent? Good idea?

I have a situation where I'm keeping references to ivars which need to be persistent. In one object, I have an array of pointers to ivars in another object, which are used over the entire lifetime of the program. In other words, I'm not just passing a reference to retrieve a value -- I'm keeping the pointers around.
Is this a valid? Is it possible that the ivars might move? Are there cases where objects instantiated objects are moved around at runtime unbeknownst to the program? Or, do objects stay exactly where they are created. If the later is the case, is there any reason not to use references the way I am?
I'm using ARC.
Note: This probably wasn't a good way to design this to begin with, but... it's all done and working 99%! (except for a nasty crash which reboots the entire phone... )
Objects and their instance variables don't move once created. However, you also need to keep a strong reference to the object that holds the ivar. Otherwise, the object might be deallocated, leaving you with a dangling pointer.
Note that it is generally a very bad idea to have pointers to another object's insntance variables.
While there's no technical problem with accessing the ivars from outside (as rob stated) there's still the architectural design to consider: The approach you've taken breaks encapsulation. Additionally it is very uncommon for Objective-C.
So regarding maintainability of your code I would recommend to refactor the code. In Objective-C there's no friend declaration as in C++, so it's unusual to access ivars from outside the declaring class.
Let's say an object of class A wants to access the ivars of an object of class B persistently (in your example).
What you normally do is create a property (with the strong annotation, like #property (strong) ClassB *myBVar) in class A to reference an object of class B.
If you want to set or read B's properties you use the dot notation or call the getter/setter methods:
myBVar.name = #"Jim";
NSLog(#"Name:%#",myBVar.name);
[myBVar setName:#"Jim"];
NSLog(#"Name:%#",[myBVar name]);
You never call a ivar directly as it's implementation might change.

Do all objects occupy similar amounts of memory? Objective-c

If I make my object a subclass of UIViewController, does it use substantially more memory than if it is a subclass of NSObject? A ballpark figure for how much more overhead is used by subclassing a complex class vs a simple one would be great. edit: or a way to figure out the difference myself.
You can imagine that an objective-c object is just a C structure that looks like this:
typedef struct {
Class isa;
} NSObject;
An instance of that structure would take 4 bytes on a 32-bit system. Since it's composed of a single pointer - Class is similar to id.
A subclass of NSObject, MySubclass with one 'char' instance variable would look like this:
typedef struct {
Class isa;
char singleInstanceVariable.
} MySubclass;
A subclass simply has all of the instance variables of its super class at the beginning, plus its own at the end. You can see this in the debugger by typing 'p *object' in the console.
MySubclass's size would be 5 bytes on a 32-bit system. One pointer, plus one char. So, an object's size is the size of all of it's instance variables added together. One important thing to know is that an object's size is only related to its instance variables. It isn't impacted by the number of methods it has. Those methods don't cost any extra memory as more instances are instantiated. Methods have a fixed initial cost.
Another thing to consider is that objects usually have pointers to other objects as instance variables. For example, let's say every UIView has an NSMutableArray to reference its subviews. That array might be 12 bytes when empty. So an empty UIView would be the size of all of the variables in a UIView, which would include 4 bytes for the pointer to an array, plus you might also account for the 12 additional bytes used by the actual array instance. That's all just accounting though, the array and the view are two distinct objects, but the view isn't really usable without the array.
Lastly, most allocations are rounded up to some quantum in order to make the malloc implementation faster and to satisfy some constraints of the architecture of the machine so that pointers are properly aligned. Also an object's instance variables might have empty padding in between them similar to structure padding
That depends on the number and nature of the superclass's instance variables. NSObject has one ivar, the isa pointer. UIViewController has about 30 ivars, most of them pointers (you can look the list up in UIViewController.h).
So any subclass of UIViewController will take up as much memory as is needed to store all those ivars and all ivars of its superclasses (UIResponder (no ivars) and NSObject (one ivar)).
This calculation does not take into account the actual memory that is used by the objects these instance variables reference when initialized, of course. For example, a fully initialized view controller may hold on to a view object that takes up a considerable amount of memory.
Try class_getInstanceSize([MyClass class]);. Roughly speaking, the memory usage of an instance will be this value rounded up to a multiple of sixteen bytes. Of course, this doesn’t include overhead of any associated objects (see objc_setAssociatedObject) or allocations the class makes.
In short, yes, but probably not enough that you need to worry about it unless you're planning on instantiating tens thousands of them.
The object will allocate memory for each of its ivars and its methods. The amount of memory needed depends on the C types... they all vary according to the datatype what's being stored.
The amount of memory used depends on how the object is instantiated, presented on screen, and interacted with. For example, a subclass of NSObject will not have any interaction with the user's touches.
You can always attach you application with the Instruments Allocations performance tool to compare the difference.

Objective-c: Objects by value / Structs with methods / How can I get something like that?

I'm starting to code in objective-c and I've just realized that objects can only be passed by reference.
What if I need an object to use static memory by default and to be copied instead of referenced?
For example, I have an object Color with 3 int components r, g and b. I dont want these objects to be in dynamic memory and referenced when passing to functions, I want them immutable and to be copied like an int or a float.
I know I can use a c struct, but I also need the object Color to have methods that gets/sets lightness, hue, saturation, etc. I want my code to be object oriented.
Is there any solution to this?
EDIT: If for example I'm building a 3d game engine, where I'll have classes like Vector2, Vector3, Matrix, Ray, Color, etc: 1) I need them to be mutable. 2) The size of the objects is roughly the same size of a pointer, so why would I be copying pointers when I can copy the object? It would be simpler, more efficient, and I wouldnt need to manage memory, specially on methods that returns colors. And In the case of a game engine, efficiency is critical.
So, if there is no solution to this... Should I use c-structs and use c-function to work on them? Isn't there a better choice?
Thanks.
You can't do this. This isn't how Objective-C works (at least the Apple/GNU version*). It simply isn't designed for that sort of extreme low-level efficiency. Objects are allocated in dynamic memory and their lifetimes are controlled by methods you call on them, and that's just how it works. If you want more low-level efficiency, you can either use plain C structs or C++. But keep in mind that worrying about this is pointless in 99% of circumstances — the epitome of premature optimization. Objective-C programs are generally very competitive with C++ equivalents both in execution speed and memory use despite this minor inefficiency. I wouldn't go for a more difficult solution until profiling had proved it to be necessary.
Also, when you're new to Objective-C, it's easy to psych yourself out over memory management. In a normal Cocoa (Touch) program, you shouldn't need to bother about it too much. Return autoreleased objects from methods, use setters to assign objects you want to keep around.
*Note: There was an old implementation of Objective-C called the Portable Object Compiler that did have this ability, but it's unrelated to and incompatible with the Objective-C used on Macs and iOS devices. Also, the Apple Objective-C runtime includes special support for Blocks to be allocated on the stack, which is why you must copy them (copy reproduces the block in dynamic memory like a normal object) if you want to store them.
What if I need an object to use static memory by default and to be copied instead of referenced?
You don't.
Seriously. You never need an object to use static memory or be allocated on the stack. C++ allows you to do it, but no other object oriented language I know does.
For example, I have an object Color with 3 int components r, g and b. I dont want these objects to be in dynamic memory and referenced when passing to functions, I want them immutable and to be copied like an int or a float.
Why do you not want the objects to be in static memory? What advantage do you think that gives you?
On the other hand it's easy to make Objective-C objects immutable. Just make the instance variables private and don't provide any methods that can change them once the object is initialised. This is exactly how the built in immutable classes work e.g. NSArray, NSString.
One solution that people use sometimes is to use a singleton object (assuming you only need one of the objects for your entire app's lifetime). In that case, you define a class method on the class and have it return an object that it creates once when it is first requested. So you can do something like:
#implementation MyObject
+ (MyObject *)sharedObjectInstance
{
static MyObject *theObject=nil;
if (theObject==nil)
{
theObject = [[MyObject alloc] init];
}
return theObject;
}
#end
Of course the object itself isn't what's being statically allocated, it's the pointer to the object that's statically allocated, but in any case the object will stick around until the application terminates.
There are times when you want to do this because you really only want one globally shared instance of a particular object. However, if that's not your objective, I'm not sure why you'd want to do what you're describing. You can always use the -copy method to create a copy of an object (assuming the object conforms to the NSCopying protocol) to manipulate without touching the original.
EDIT: Based on your comments above it seems you just want to have immutable objects that you can copy and modify the copies. So using -copy is probably the way to go.