2011-12-22 23 views
7

Tengo una NSMutableArrayañadiendo objeto NSInteger a NSMutableArray

@interface DetailViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> { 

NSMutableArray *reponses; 
} 
@property (nonatomic, retain) NSMutableArray *reponses; 

@end 

y estoy tratando de agregar en mi arsenal NSInteger objeto:

@synthesize reponses; 



NSInteger val2 = [indexPath row]; 
[reponses addObject:[NSNumber numberWithInteger:val2]]; 
NSLog(@"the array is %@ and the value is %i",reponses, val2); 

no funcionará el objeto no ha sido añadido a la matriz, esto es lo que muestra la consola:

the array is (null) and the value is 2 

Respuesta

4

usted no es inicializar la matriz, lo que es todavía nil cuando intentas agregar algo.

self.responses = [NSMutableArray array]; 
//now you can add to it. 
+0

es correcto thx –

1

No ha inicializado la matriz de respuestas. En su código, puede ser viewDidLoad, do:

reponses = [[NSMutableArray alloc] init]; 

A continuación, agregue el objeto a su matriz.

NSInteger val2 = [indexPath row]; 
[self.reponses addObject:[NSNumber numberWithInteger:val2]]; 

Eso debería funcionar.

8

@Omz: tiene razón. Asegúrese de tener la matriz asignada e inicializada. Compruebe el siguiente código

NSMutableArray *array = [[NSMutableArray alloc] init]; 
NSInteger num = 7; 
NSNumber *number = [NSNumber numberWithInt:num]; 
[ar addObject:number]; 
NSLog(@"Array %@",array); 

Lo he comprobado y funciona. Si array ya no es necesario, asegúrese de release.

+0

para gente nueva (me), para convertir NSNumber a NSInteger (cuando se recupera información de la matriz), 'NSInteger num = [number integerValue];' (gracias 7KV7) – tmr