PDA

View Full Version : const initialization in Objective-C




xjayx
Jan 11, 2009, 03:49 PM
@interface Megatron : NSObject {
NSString * const RANK;
}
@end

How do i initialize RANK?

Basically, I'm looking for the Objective-C equivalent to the following C++ program.

class Megatron {
private:
const std::string RANK;
public:
Megatron();
void print();
};

#include <stdio.h>
#include <string>
#include <iostream>
#include "Megatron.h"

Megatron::Megatron(): RANK("Leader") {
}

void Megatron::print() {
std::cout << RANK << "\n";
}



gnasher729
Jan 11, 2009, 04:08 PM
@interface Megatron : NSObject {
NSString * const RANK;
}
@end

How do i initialize RANK?


You don't. Objective-C doesn't work that way. You are also a bit confused: RANK would be a pointer variable that cannot be modified. Your C++ example had an _object_ that cannot be modified, which is a completely different thing.

Since NSString objects are non-modifiable anyway, you just write

NSString* RANK;

And all uppercase identifiers for class members are beyond ugly.

toddburch
Jan 11, 2009, 04:31 PM
If I understand the text properly, from pages 197-199 in Programming on Objective-C, you do this to get the effect of a class variable in Objective-C:

In your @implementation file, define it as a static variable outside the @implementation section:

// Implementation file

static NSString * Rank = @"Leader" ;

@implementation MyClass
...
@end


You have the choice (it's optional) to redeclare your static var (as extern) in your methods, like this:

@implementation MyClass

static NSString * Rank = @"Leader"

+(NSSring *) getRank {
extern NSString * Rank ; // this line is optional and for the reader
return Rank ;
}

@end


(Caution - I'm still learning the language!!)

xjayx
Jan 11, 2009, 06:12 PM
In your @implementation file, define it as a static variable outside the @implementation section:


That is exactly what I want to do. Thanks.

However, I still don't understand why I can't have a constant instance pointer.

gnasher729
Jan 11, 2009, 07:18 PM
That is exactly what I want to do. Thanks.

However, I still don't understand why I can't have a constant instance pointer.

1. Your C++ example showed an instance variable. I think you need to make up your mind whether you want a member variable (can have different values in different objects) or a class variable (only once per class).

2. You can have a constant pointer as an instance variable, you just can't modify it (which makes it rather pointless). The only time you can modify a constant instance variable in C++ is within the constructor; the init method in Objetive-C is a method like any other without any special privileges and cannot modify any constant instance variables.