views:

80

answers:

2

Wondering if there's any accepted practice for approximating C++'s 'const methods' in Objective-C. (new to the language from a C/C++ background)

For instance:

class Foo {
  public:
     void canChangeMemberVars(void);
     char* asString(void) const;
};

"asString()" gets a const this pointer, so even if you go rogue and decide to muck around with the instance's members it won't work. I find labelling methods as const to be quite useful from a documentation standpoint for libraries I write.

I'm in the midst of writing an Objective-C class library, and find myself wanting to be able to make specific methods const, and wondering if there's any language tricks to achieve this.

Summarized:

At the end of the day is the the only way to achieve similar functionality to factor classes in Mutable and Immutable versions? Making a simple note in the comments for each method isn't rigid enough for my purposes.

+5  A: 

Yes, your only option if you want to have a class that sometimes can be mutated and sometimes can't is to make mutable and immutable versions of the class. You'll notice this is how Apple does it in Cocoa (NSArray, NSSet, NSDictionary, NSString, etc.) — following Apple's conventions is usually the best way to go.

Objective-C really doesn't even have a concept of a const object. Even if you do declare an object pointer const, that doesn't prevent you from calling methods on the object that set variables.

Chuck
A: 

You can make members of the class private with @private and provide read-only accessors (by using @property (readonly) or simply writing only a getter).

Anyway, Mutable : Immutable is how it's done in ObjC.

porneL