2010-05-21 28 views

Respuesta

8

Puede inicializar la matriz con un conjunto de objetos:

NSString * blah = @"SO"; 
NSArray * items = [NSArray arrayWithObjects: blah, blah, nil]; 

o puede utilizar una matriz mutable y añadir los objetos después:

NSMutableArray * mutableItems = [[NSMutableArray new] autorelease]; 
for (int i = 0; i < 10; i++) 
    [mutableItems addObject:blah]; 
2

hay que añadirlas con initWithObjects: (o el método que prefiera). Un NSArray no requiere que sus objetos sean únicos, por lo que puede agregar el mismo objeto (u objetos iguales) varias veces.

3

Si no desea utilizar matrices mutables y no quieren repetir su identificador N veces, utilizar esa NSArray se puede inicializar de una matriz de estilo C:

@interface NSArray (Foo) 
+ (NSArray*)arrayByRepeatingObject:(id)obj times:(NSUInteger)t; 
@end 

@implementation NSArray (Foo) 
+ (NSArray*)arrayByRepeatingObject:(id)obj times:(NSUInteger)t { 
    id arr[t]; 
    for(NSUInteger i=0; i<t; ++i) 
     arr[i] = obj; 
    return [NSArray arrayWithObjects:arr count:t];  
} 
@end 

// ... 
NSLog(@"%@", [NSArray arrayByRepeatingObject:@"SO" times:10]); 
2

Ahora , puede usar una sintaxis literal de matriz.

NSArray *items = @[@"SO", @"SO", @"SO", @"SO", @"SO"];

Puede acceder a cada elemento como el items[0];

4

Mi ¢ 2:

NSMutableArray * items = [NSMutableArray new]; 
while ([items count] < count) 
    [items addObject: object]; 
Cuestiones relacionadas