Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C - define an enum than can be dot called like ENUMTYPE.ENUMVAL

I've read many things about enum types in objective-c, and I see there is many ways to define them. But I don't see the right way (if there is one) to define an enum that can be called with CARS.ROLLSROYCE and that cannot be used only with ROLLSROYCE in the code.

So I can define ROLLSROYCE in the CARS enum and also in the BEAUTIFULCARS enum.

Do you know the way to define such an enum ?

like image 520
Oliver Avatar asked Jan 16 '11 01:01

Oliver


1 Answers

You are trying to implement namespaces for your Enums in Objective-C. What you're asking for is a lot of elbow grease in Objective-C. You are probably best-off using C++ for this, since it is easy and afaik fully supported in any iOS or Cocoa application. You'll have to rename the files that #import your C++ code to .mm files instead of .m files, and the C++ compiler can be trickier than the Objective-C one. Going this route you'll create a header file like Enums.h.

//  Enums.h
namespace CARS
{
    enum CARS
    {
        ROLLSROYCE
    };
}
namespace BEAUTIFULCARS
{
    enum BEAUTIFULCARS
    {   
        ROLLSROYCE = 45
    };
}

And in your .mm sourcefile

#import "Enums.h"

-(void)printEnumvals
{
    NSLog(@"CARS %d BEAUTIFULCARS %d",
                     CARS::ROLLSROYCE,
            BEAUTIFULCARS::ROLLSROYCE);
}

If you want to avoid using C++ for this solution, there's a lot more elbow grease, bookkeeping, and opportunity for error. You'll need a header and a source file for this.

// CARS.h
@interface BEAUTIFULCARS : NSObject
{
    enum
    {
        BEAUTIFULCARS_ROLLSROYCE = 45
    } BEAUTIFULCARS;
}
@end
@interface CARS : NSObject
{
    enum
    {
        CARS_ROLLSROYCE
    } CARS;
}
@end

// CARS.m
@implementation BEAUTIFULCARS
+(NSInteger)ROLLSROYCE{ return BEAUTIFULCARS_ROLLSROYCE; }
@end
@implementation CARS
+(NSInteger)ROLLSROYCE{ return CARS_ROLLSROYCE; }
@end

Your .m source is almost the same:

#import "CARS.h"

-(void)printEnumvals
{
    NSLog(@"CARS %d BEAUTIFULCARS %d",
                     CARS.ROLLSROYCE,
            BEAUTIFULCARS.ROLLSROYCE);
}

Objective-C does not manage scope in the same way that most other OO languages do. Interfaces define the properties and messages that an object that interface supports, but don't support protection levels like public or private. When you define an enum in an @interface, that enum ends up in global scope.

like image 185
Thomson Comer Avatar answered Apr 28 '23 06:04

Thomson Comer