Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an approximation of C++'s "const methods" exist for Objective-C?

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.

like image 882
John Carter Avatar asked Nov 01 '25 12:11

John Carter


2 Answers

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.

like image 187
Chuck Avatar answered Nov 04 '25 03:11

Chuck


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.

like image 28
Kornel Avatar answered Nov 04 '25 02:11

Kornel