Friday, 8 January 2016

Enumeration in Objective C

Enum (enumerated type) is an user-defined type that is used in Objective-C to represent the data that can be stored in one of several predefined values (all of them are int).


Let’s imagine you have to implement a simple UIView that has three different visual modes: default (grey), green and red. Each mode is represented to user by three different pictures: my_mode_grey.pngmy_mode_green.png and my_mode_red.png. All of three final views would have some common behavior. 

To understand it , lets take an example:

1) First create an enum

enum myMode {
         
         myViewModeDefault,  //== 0(by default)
         myViewModeGreen,   //  == 1 (incremented by one from previous)
         myViewModeBlue    // ==2 

};


It means that every “mode” is simply described by the unique int value (unique inside current enum). Each next enum mode is incremented by 1 by default. You can also set the enum mode values by yourself (if you really need it):


enum myMode {
         
         myViewModeDefault = 5,  //== 5 (redefined)
         myViewModeGreen,   //  == 6 (incremented by one from previous)
         myViewModeBlue  = 9   // ==2 

};

2) Now lets create a class:

#import <UIKit/UIKit.h>
@interface MyViews:UIView{

    enum myMode mode ;

}
-(id)initWithMode:(enum myMode)amode;

@end


3) implement our custom initializer:

@implementation MyViews

-(id)initWithMode:(enum myMode)amode{
      
             self = [super init];
            
             if(self){
                   mode = amode;
             

       //to store different images

      NSString  *imageName;
    
         switch(amode){
             
       case myViewModeDefault:
                               imageName = @"tom.png"
                                break; 
       case myViewModeDefault:
                               imageName = @"jery.png"
                                break; 

     case myViewModeDefault:
                               imageName = @"draculla.png"
                                break; 

     default:
                  imageName = @"sorry.png"
                                break; 
}

      UIImageView *imageView = [UIImageView alloc]initWithImage:[UIImage imageNamed: imageName]];

     [self addSubview:imageView];
}

return self;

}

@end



Thats it, how easy it is.

No comments:

Post a Comment