2012-01-25 255 views
0

假设我想用50个整数填充NSarray。我们知道NSarray只接受对象。所以,我必须做50次用整数填充数组

NSNumber *num1 = [NSNumber numberWithInit:10]; 
NSNumber *num2 = [NSNumber numberWithInit:212]; 
...... 
NSNumber *num50 = [NSNumber numberWithInit:12]; 

是否有更优雅的方式来实现这一目标,东阳看起来愚蠢的50行的代码只对创建数量的对象?

+0

都是这些整数硬编码?我的意思是你需要输入50个整数的原因是什么? –

+0

一般问.. – objlv

+0

整数是随机选择的吗?或者你有固定的名单?我相信你可以用任何一种方式来使用循环。 –

回答

0

如何使用NSMutableArray

NSMutableArray* arr = [[NSMutableArray alloc] init]; 
int i = 0; 
for(i=0; i<50; i++) { 
    NSNumber* num = [NSNumber numberWithInt:i]; // use i or random numbers 
    [arr addObject:num]; 
} 
+1

发布数量.. :) –

+1

不,代码是正确的。因为它是一个自动释放对象,所以不需要释放'num'。 –

+0

num没有被分配,它是使用便利的建筑师创建的,所以它不应该被释放 –

0

试试这个...

NSMutableArray *array=[[NSMutableArray alloc]initWithCapacity:50 ]; 

    for (int i=0; i<0; i++) { 
     NSNumber *number=[[NSNumber alloc] initWithInt:i]; 
     [array addObject:number]; 
     [number release]; 
    } 
//do anything with arrray and release the array later. 

这是正确的,或者您正在寻求别的?

0

你的号码似乎不遵循任何特定的模式,所以你可能会更好做这首先创建一个C数组:

int myValues[] = { 10, 212, ..., 12 }; 
NSUInteger count = sizeof(myValues)/sizeof(int); // number of integers in myValues 

// abstract the following into a function/method/category if doing more than once 
NSMutableArray *objcValues = [NSMutableArray arrayWithCapacity:count]; 
for(NSUInteger ix = 0; ix < count; ix++) 
    [objcValues addObject:[NSNumber numberWithInt:myValues[ix]];