objective-cvariablesscopensenumerator

Can't figure out NS_ENUM. Can I change the values inside it?


I am VERY new to Objective-C. I was having a problem with this :

NS_ENUM(NSUInteger, SetOfValues)
{ 
    firstRow = 0,
    secondRow,
    thirdRow,
    rowCount
};

Now, I need to change these variables in the implementations :

@implementation BillyBurroughs 
...

- (void) modifyrowInformation
{
    secondRow = 0;
    thirdRow = 1;
    rowCount = 2
}

@end

But of course, I get an error saying - cannot assign value. Now, I can simply read the variables to local variables like

+ (void) initialize {
    localFirstRow = 0 
    ...
}

and then modify them, but is there a cleaner and lazier way to do this without the extra variables? Sorry if this is a very basic question. I appreciate your inputs.


Solution

  • enums are constants, you cant change their value and why do you want to? thats what ivars are for.

    NS_ENUM is a nice macro apple gave us which expands to something like the following:

    typedef enum {
        firstRow = 0,
        secondRow,
        thirdRow,
        rowCount,
    } SetOfValues;
    

    NB: 0 is initialised by default for the first element unless specified.

    It is also good practice to namespace your enums to avoid collisions, maybe take a look at apples implementation and apply it to your own use case:

    typedef NS_ENUM(NSInteger, UITableViewCellStyle) {
        UITableViewCellStyleDefault,
        UITableViewCellStyleValue1,
        UITableViewCellStyleValue2,
        UITableViewCellStyleSubtitle
    };
    

    Maybe what you are looking for is a property or an array?

    array = @[ @1, @2, @3, @4 ];
    

    edit for question in comments:

    In your implementation file (.m) you can create a private header:

    @interface OKAClass ()
      @property (nonatomic, assign) NSUInteger property;
    @end
    

    You then may access the property from within that class using self or _property

    e.g.

    self.property = 1;
    

    or

    _property = 1;
    

    The difference is that the self.property uses the generated accessors and is probably what you want to be using, this will future proof you incase you wish to override the getter/setter to update another value.