When objects don't get added to arrays

Iritscen

Mr. Grumpikins
I am simply trying to do this:

Code:
NSMutableArray *ray;
[ray initWithCapacity:5]; // or whatever number
NSNumber *q;
[q initWithInt:8];

[ray addObject:q];

Hopefully the above code, reconstructed from memory since I'm not at my Mac, will give the result that nothing is added to the array, because that's what's happening in my program. Am I supposed to be using the retain command somewhere? I feel like I'm missing a basic piece of knowledge about Obj-C.

In the past, I have eventually gotten this kind of thing to work by diddling around with it. Looking at some code I wrote three years ago, I got all kinds of numbers within arrays within arrays working just fine, and yet I can't see why it works and this doesn't. Frustrating.
 
Assuming that code is complete, the problem is that you have not alloc'd the array. Right now you're initializing an object that doesn't exist — or rather, you're treating whatever random data *ray happens to point to as an NSMutableArray.

So, simply change that second line to:
ray=[[NSMutableArray alloc] initWithCapacity:5];

The alloc method creates space for the object in memory and returns a pointer to that memory. init methods take that memory and populate it with meaningful data, returning a pointer (usually, but not necessarily the same as what alloc returned) to a ready-to-use object.

You are responsible for releasing objects you create with -alloc, -new or -copy.

Edit: Oh, and you'll need to make similar changes to *q.
 
This is the thing that has always bit me in the butt. Is there a particular reason why objective-C requires a separate call to the alloc method? This is terribly unintuitive to programmers coming from languages where constructors exist.
 
Back
Top