0

I just started learning Objective C and I am trying to populate an array using the following method:

#import "ArrayCreator.h"

@implementation ArrayCreator
-(int) ArrayCreator: (int) size{
    int i;
    int a[size];
    for (i=0; i<size; i++) {
        a[i] = i+5;
    }
    return a;   // Xcode give a warning here!!
}
@end

where size is parameter to be defined in the main.m document later. I am a bit confused on how to define this type of mutable array. I know of the existence of NSMutableArray, although I have seen in forums that people would rather use int a[size] to define this objects.

3 Answers 3

2

You're declaring that array on the stack, which means that it will automatically be destroyed as soon as you return. You need to use malloc() and free() if you want to use C arrays. Using NSMutableArray is generally much simpler and safer though; if you don't need to use C arrays, you shouldn't.

Sign up to request clarification or add additional context in comments.

Comments

1

There isn't really a need to make that class. Here's how you make a NSMutableArray:

NSMutableArray *array = [NSMutableArray arrayWithCapacity:desiredSize];
for (i = 0; i < desiredSize; i++) {
    [array addObject:[NSNumber numberWithInt:(i + 5)]];
}

You could use

NSMutableArray *array = [NSMutableArray array];

instead but since you know the size it is a little more efficient to specify it.

You're getting an error from Xcode because you are trying to return an array when the method says you will return an int. You could specify the method returns a pointer to the array, but you don't need (or want) to stick with C arrays when doing iOS development. It seems like a pain to have to make all the ints a NSNumber object at first, but you will find it much easier to work with the SDK if you get used to it.

Comments

1

Xcode gives you a warning because you it's unsafe to return a from that method. a is created on the stack, and so it will essentially "disappear" from memory once the method returns, so a will not be pointing to valid memory.

(Also, you're not returning an int from the function, but rather an int *.)

To allocate a on the heap, so it outlives the execution of the method, you have to use malloc (or a related function):

-(int *) ArrayCreator: (int) size{
    int i;
    int a = malloc(sizeof(int) * size);
    if (!a) {
        NSLog(@"memory error");
        return NULL;
    }
    for (i=0; i<size; i++) {
        a[i] = i+5;
    }
    return a;
}

Of course, the caller will be responsible for calling free on the returned value.

Really, it's probably easier to just use an NSArray, and there aren't a lot of drawbacks vs. returning an int array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.