Search code examples
iospropertiesnsmutablearrayenumerated-types

getting NSMutableArray Property filled with enumerated values


Attempting to get an enumerated value by an index from a NSMutableArray property that is filled with enumerated values.

all I wanted is to set a dynamic property and get set back within class instance.

thus, I coded a clear example that expose of problem.

Problem is this. WriteByType method in example never gets correct value. it should log "You Get Right Arrow" but it doesn't

//----------------------------------------------------------
//  CCMyClass.h
#import <Foundation/Foundation.h>

typedef enum {
    aLeft,
    aRight
} Arrow;

@interface CCMyClass : NSObject
{
    NSMutableArray *_arrowsPkg;
}
@property(nonatomic,copy) NSMutableArray *arrowsPkg;
@property (nonatomic)int nextPkgIndex;
-(void)GetItemOne;
@end
//-------------------------------------------------------------
//  CCMyClass.m
#import "CCMyClass.h"

@implementation CCMyClass
@synthesize arrowsPkg=_arrowsPkg;

-(void)WriteByType:(Arrow)AArrow
{
switch (AArrow) {
    case aLeft:
        NSLog(@"You Get Left Arrow");
        break;
    case aRight:
        NSLog(@"You Get Right Arrow");
        break;
    }
}

-(void)GetItemOne
{
    Arrow a =(Arrow)[[self arrowsPkg]objectAtIndex:1];
    [self WriteByType:a];

}
@end
//---------------USAGE EXAMPLE----------------------------------------------
//  CCAppDelegate.m
- (IBAction)btn1Clicked:(id)sender {

    CCMyClass *c1=[[CCMyClass alloc]init];
    NSNumber *v1=[NSNumber numberWithInt:aLeft];
    NSNumber *v2=[NSNumber numberWithInt:aRight];

    NSMutableArray *arr1=[NSMutableArray arrayWithObjects:v1,v2, nil];
    [c1 setArrowsPkg:arr1];
    [c1 GetItemOne];
}

Solution

  • Replace

    Arrow a = (Arrow)[[self arrowsPkg] objectAtIndex:1];
    

    with

    Arrow a = (Arrow)[[[self arrowsPkg] objectAtIndex:1] intValue];
    

    or, more clearly written

    NSNumber *arrowNumber = [[self arrowsPkg] objectAtIndex:1];
    Arrow a = [arrowNumber intValue];
    

    You are storing your Arrow enum types in NSNumber in btn1Clicked:, so you need to unbox these values in GetItemOne from NSNumber * types to the earlier int values.