-2

I am trying to add an object of the same class to a NSMutable array that is defined in the same class. My approach would look like this, but when I tested the array, it was always empty. I also tried adding random Strings or integers.

The .h file:

@property NSMutableArray *anArray;
- (void)addObject: (TheClass*)nameOfObjectToBeAdded;

The .m file:

@synthesize anArray;

- (void)addObject: (TheClass*)nameOfObjectToBeAdded {
    [anArray addObject:nameOfObjectToBeAdded];
}

The main.m:

#import "TheClass.h"

int main(int argc, char *argv[])
{
    @autoreleasepool {

        TheClass *object1 = [[TheClass alloc] init];
        TheClass *object2 = [[TheClass alloc] init];
        [object1 addObject:object2];

    }
    return 0;
}

I am trying to add object2 to the NSMutableArray of object1.

Thanks in advance!

3 Answers3

3

You need to allocate and initialize the array before using it:

In Class.m, probably in init:

self.anArray = [[NSMutableArray alloc] init];
kevboh
  • 5,207
  • 5
  • 38
  • 54
1

You need to create NSMutableArray at first..

NSMutableArray *anArray = [NSMutableArray array];
[anArray addObject:object];
beryllium
  • 29,669
  • 15
  • 106
  • 125
0

Add the allocation in your classes initializer as such:

In ThisClass

-(id) init: {
  self = [super init];
  if(self) {
    self.anArray = [[NSMutableArray alloc] init];
    /* ... other initializer stuff ... */
  }
  return self;
}
lukecampbell
  • 14,728
  • 4
  • 34
  • 32