How to share constants (enumerations) between classes?

I have UIPopoverViewControllersthat send messages for delegation UIViewControllersto send user interface events. Instead of writing a separate method for each event, I have a method in the delegate with the switch statement that determines how to handle the event based on the passed constant (example below).

This is probably a bad design, but this is what I came up with. I saw this question regarding enums or static classes, but didn't understand the answers.

So, I am doing BAD , and is there a way that I can define the enumerations in one place, so that I do not need to support multiple bits of code that can easily go out of sync?

EDIT Well, dig a little more ( here + here ) I see that I can be on the right track. Therefore, I think I need to know what and where the file is implementationin iOS.

enum {
kSetPlaybackType = 0,
kSetAllNotesOn,
kSetAllNotesOff,
kSetVelocity,
kSetDuration
};

- (void)barPropertyAction:(int)action withParam:(NSNumber *)param
{
switch (action) {
    case kSetPlaybackType:
        playbackType = [param intValue];
        if (playbackType == kPalindrome){
            palindromeDirection = kPalindromeUp;
        }
        break;

    case kSetAllNotesOn:
        for (BarNote* note in self.barNoteArray) {
            note.noteOn = YES;
        }
        [self.bar updateWindows];
        break;

    case kSetAllNotesOff:
        for (BarNote* note in self.barNoteArray) {
            note.noteOn = NO;
        }
        [self.bar updateWindows];
        break;

    case kSetVelocity:
         for (BarNote* note in self.barNoteArray) {
            note.velocity = [param intValue];
        }
        break;

    case kSetDuration:
        for (BarNote* note in self.barNoteArray) {
            note.duration = [param floatValue];
        }
        break;

    default:
        break;
}
}
+5
source share
1 answer

I'm not going to say that your approach is bad, but it is slightly related to the starting embryo of the โ€œdivineโ€ method, which is a method that tries to do everything. However, for the number of options that you have in your code, I would say that it works great.

But sharing enum around is very simple. Just put them in your .h file and import it where necessary. You can include the .h file as one of the file types in the "C and C ++" section.

, , #, , , , .h "" . Objective-C ( C ++) , .

, enum :

typedef enum {
  kSetPlaybackType = 0,
  kSetAllNotesOn,
  kSetAllNotesOff,
  kSetVelocity,
  kSetDuration
} SetEnumType;

enum typedef, . .. :

int varName = kSetAllNotesOn;

:

SetEnumType varName = kSetAllNotesOn;

XCode , , , varName , .

, varNum enum int , .

,

- (void)barPropertyAction:(SetEnumType)action withParam:(NSNumber *)param

, ( , enum int). ,

- (void)barPropertyAction:(int)action withParam:(NSNumber *)param
{
switch ((SetEnumType)action) {
    case kSetPlaybackType:
        playbackType = [param intValue];
+14

All Articles