Search code examples
iphoneobjective-carraysprimitive

Declaring, Properties, Synthesizing, and Implementing int[] array in Objective C


How do you declare, set properties, synthesize, and implement an int array of size 5 in Objective C? I'm writing this code for an iphone app. Thanks.


Solution

  • I think the "Cocoa-y" thing to do is hide the int array even if you use it internally. Something like:

    @interface Lottery : NSObject {
        int numbers[5];
    }
    
    - (int)numberAtIndex:(int)index;
    - (void)setNumber:(int)number atIndex:(int)index;
    @end
    
    @implementation Lottery
    
    - (int)numberAtIndex:(int)index {
        if (index > 4)
            [[NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"Index %d is out of range", index] userInfo:nil] raise];
        return numbers[index];
    }
    
    - (void)setNumber:(int)number atIndex:(int)index {
        if (index > 4)
            [[NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"Index %d is out of range", index] userInfo:nil] raise];
        numbers[index] = number;
    }