Immutable Objects

Immutable Objects

Post by Michael J. Bergi » Tue, 24 Jun 2003 11:32:10



How do I prevent the address that a pointer references from being changed?
For example I might have the following:

static MyType *typeInstance = [[MyType alloc] init];

...

- (MyType *)getTypeInstance {
    return typeInstance;

Quote:}

Now users of my class are able to reassign the memory referenced by the
pointer returned so they could assign another instance of MyType to the
pointer.  I've tried MyType* const typeInstance and it gives me a compiler
warning but that's it.  Is there any way to do this or am I misunderstanding
pointers?
 
 
 

Immutable Objects

Post by Michael As » Tue, 24 Jun 2003 12:51:27




Quote:> How do I prevent the address that a pointer references from being changed?
> For example I might have the following:

> static MyType *typeInstance = [[MyType alloc] init];

> ...

> - (MyType *)getTypeInstance {
>     return typeInstance;
> }

> Now users of my class are able to reassign the memory referenced by the
> pointer returned so they could assign another instance of MyType to the
> pointer.  I've tried MyType* const typeInstance and it gives me a compiler
> warning but that's it.  Is there any way to do this or am I misunderstanding
> pointers?


ever seems to use), you cannot directly access the memory of an object
even if you have a pointer to it. And an assignment like this:

object1 = object2;

This only modifies the *pointer*, it does not modify what's *pointed to*.

To make an object "immutable", you must do two things. Once, don't

indication that you're doing something wrong anyway, so that's a
no-brainer. Two, don't provide any methods for changing the object!
Since the only way people can change your object is by messaging it,
deny them any messages which can change the object and your object is
immutable.

Note that in Objective-C, you cannot dereference a pointer to an object,
nor can you have a variable directly hold an object, rather than a
reference to one. A statement like *object1 = *object2 is illegal.