1

I know that to create array with integers in Object-c they have to be objects. So If I want array with integer I should create them like that:

NSNumber *myArrayInteger = [NSNumber NumberWithInteger:2];

So far, so good. But what If I wan`t array to consist of lets say more than 30 integers. Should I use code above for each of them or there is a more friendly solution ?

1
  • A normal C array would be lot more easier. int myArrayInteger[30]; Commented Mar 5, 2011 at 9:01

2 Answers 2

3

NSArray can contain only objects, not primitive types like int, float etc. So you need to wrap them with NSNumber object. For 30 integers you need to wrap them all in NSNumber, may be by using a loop if possible.

But one thing that Obj-C is a super set of C. So you can use a pure C array of int if you want. Sometimes (specially for higher dimensional array) they are more suitable to maintain.

int arr[30];
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I know the "C" solution, but I`m curious how to do in Objective-c. Using loop for such a task looks strange.
For many things Obj-C depends on C. For example, we need to use C syntax for pointer. Same goes for array too. If you think C array will be good, then use it. There is no problem, neither that is bad practice. Obj-C itself does not have any special syntax for array.
3

Personally, I find myself using arrays of integers so often that I had to streamline the process a bit. For instance:

NSArray myList=klist(4,2,3,2,3);

is equivalent to something like:

NSArray myList = [NSArray arrayWithObjects:
    [NSNumber numberWithInt:2],
    [NSNumber numberWithInt:3],
    [NSNumber numberWithInt:2],
    [NSNumber numberWithInt:3],nil];

Here are the functions that I use:

#define kInt(x) [NSNumber numberWithInt:x]
#define kArray(...) [NSMutableArray arrayWithObjects: __VA_ARGS__,nil]
#define klist(...) [arrays iList:__VA_ARGS__]
#define k1ist(x) [arrays iList:1,x]
#define krange(x) [arrays range:x]
#define kAppend(...) [arrays append_arrays:__VA_ARGS__,nil]

@interface arrays : NSObject 
{}
+(NSMutableArray *) range:(int) i;
+(NSMutableArray *) iList:(int) n, ...;
@end

@implementation arrays
+(NSMutableArray *) range:(int) i{
    NSMutableArray *myRange = [NSMutableArray array];
    for (int I=0;I<i;I++)
    {
        [myRange addObject:kInt(I)];
    }
    return myRange;
}
+(NSMutableArray *) iList:(int) n, ...{
    int ii;
    NSMutableArray *myRange = [NSMutableArray array];
    va_list myArgs;
    va_start(myArgs,n);
    for (int i=0;i<n;i++){
        ii = va_arg(myArgs,int);
        [myRange addObject: kInt(ii)];
    }
    return myRange;
}
@end

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.