开发者

Integers in array

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 开发者_如何学GoIf 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 ?


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];


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜