1

Is there a way to use something like

if (carRecord.status == CarRecord.statusRepaired) {  // using a class constant
    // ...
}

such as in a car repair shop, the carRecord object's state status is checked against the CarRecord class's constant. In Objective-C, is there such a way?

nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • Is this what you're looking for? http://stackoverflow.com/a/980272/169277 or this one http://iphonedevelopertips.com/objective-c/java-developers-guide-to-static-variables-in-objective-c.html – ant Apr 22 '12 at 17:54

2 Answers2

7

You would typically do this with an enum. For example:

//=== CarRecord.h:
typedef enum CarRecordStatus {
    CarRecordStatusBroken = 0,
    CarRecordStatusRepaired
} CarRecordStatus;

@interface CarRecord (NSObject) {
    CarRecordStatus _status;
}

@property (nonatomic, assign) CarRecordStatus status;

@end

//=== CarRecord.m:
@implementation CarRecord

@synthesize status=_status;

- (void)someMethod {
    if (self.status == CarRecordStatusRepaired) {
         //...
    }
}

@end
omz
  • 53,243
  • 5
  • 129
  • 141
  • I think he's not looking for enum, I think he means static variable .. maybe I'm wrong – ant Apr 22 '12 at 17:57
  • so this will be defined only within the class? Or are they global constants? – nonopolarity Apr 22 '12 at 17:58
  • They are defined only within the class, and all those that import it's header. – CodaFi Apr 22 '12 at 18:00
  • The `enum` could be used anywhere you import the header in which it's defined. I'm not saying it's exactly equivalent to your code, just that it's the conventional way of approaching this problem in Objective-C. – omz Apr 22 '12 at 18:02
  • Can you put the complete code... Is it all inside the .h and how to use it inside and outside of the class? thx – nonopolarity Apr 22 '12 at 19:16
  • thanks... will you use a small `k` in front for constants? I saw some code that uses a small `k` and looks like a convention for constants – nonopolarity Apr 22 '12 at 22:42
  • So the user of this class cannot use `CarRecord.CarRecordStatusBroken` but just have to use a single name `CarRecordStatusBroken` huh? (not part of the class) – nonopolarity Apr 22 '12 at 23:43
6

Here is how would you define it in .h file :

typedef enum CarRecordStatus {
    CarRecordStatusBroken = 0,
    CarRecordStatusRepaired,
} CarRecordStatus;

@interface MyClassName : NSObject    
..interfacebody..
@end

Use it inside MyClassName or any other just import it that's it.

ant
  • 22,634
  • 36
  • 132
  • 182