0
votes

I'm trying to initialize an NSMutableArray and it's not working correctly. Subsequent access to the array throws an exception saying "index 0 beyond bounds for empty array." A breakpoint following the initialization line says that my array has a location in memory, but that it has 0 objects

Here's my attempt at the moment:

in my .h

@interface SomeInterface : NSObject 
{
@private
    NSMutableArray *myArr;
}

in my .m

- (id) initWithHeight: (int) height
{
    self = [super init];
    if (self) 
    {
        self->myArr = [[NSMutableArray alloc] initWithCapacity:height];
    }
    return self;
}

The breakpoint shows myArr = (NSMutableArray *) 0x######## 0 objects

Does anyone know how to properly initialize an NSMutableArray?

2

2 Answers

2
votes

initWithCapacity: does not create objects in your array, so the debugger isn't lying - your array is empty until you add objects to it, either by using addObject: or by initializing it with objects in the first place.

1
votes

as yonix pointed you are not creating any objects, here an example that adds your object:

.h

#import <Foundation/Foundation.h>

@interface Ssuti : NSObject 
{
    NSMutableArray *_myArr;
}

@property (nonatomic, assign) NSMutableArray *myArr;

- (id) initWithHeight: (int) height;

@end

.m

#import "Ssuti.h"


@implementation Ssuti

@synthesize myArr = _myArr;


- (void)dealloc {
     [super dealloc];
}

- (id) initWithHeight: (int) height
{
    self = [super init];
    if (self) 
    {
        self.myArr = [NSMutableArray array];

        [self.myArr addObject:[NSNumber numberWithInt:height]];

        NSLog(@"myArr :: %@", self.myArr);
    }
    return self;
}

@end

then in the ViewController you call it:

Ssuti *mySssuti = [[Ssuti alloc]initWithHeight:345];

    [mySssuti release];

;)