adding NSInteger object to NSMutableArray
Asked Answered
F

3

7

I have an NSMutableArray

@interface DetailViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {

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

@end

and i'm trying to add in my array NSInteger object:

@synthesize reponses;



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

it won't work the object was not added to the array, this is what console shows:

the array is (null) and the value is 2
Ferdy answered 22/12, 2011 at 7:51 Comment(0)
H
4

You're not initializing your array, so it's still nil when you're trying to add to it.

self.responses = [NSMutableArray array];
//now you can add to it.
Hodson answered 22/12, 2011 at 7:55 Comment(0)
H
9

@Omz: is right. Make sure you have the array allocated and initialized. Please check the following code

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

I have checked this and it works. If array is no longer needed make sure you release it.

Hines answered 22/12, 2011 at 8:3 Comment(1)
for new folks (me), to convert NSNumber back to NSInteger (when retrieving information from the array), 'NSInteger num = [number integerValue];' (thank you 7KV7)Corazoncorban
H
4

You're not initializing your array, so it's still nil when you're trying to add to it.

self.responses = [NSMutableArray array];
//now you can add to it.
Hodson answered 22/12, 2011 at 7:55 Comment(0)
C
2

You have not initialized the responses array. In your code, may be viewDidLoad, do:

reponses = [[NSMutableArray alloc] init];

Then add the object to your array.

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

That should work.

Chromatolysis answered 22/12, 2011 at 7:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.