2

I would like to assign NSInteger by using NSMutableArray is there any way to solve this? It is not working on simulator and cut off when run the application.

NSInteger Section;
NSMutableArray dataSourceSection;

Section = (NSInteger)[dataSourceSection objectAtIndex:2];

Thank you.

1
  • 2
    You have to put the integer in a NSNumber Object Commented Jun 12, 2011 at 18:46

2 Answers 2

8

A NSMutableArray only stores objects. NSInteger is not an object, but a primitive data type. There is a class NSNumber, however, that can be used instead to store numeric values inside objects. Here's one example.

NSNumber *five = [NSNumber numberWithInteger:5];
NSMutableArray *numbers = [NSMutableArray array];
[numbers addObject:five];

To get the object back and retrieve the integer value use,

NSNumber *firstNumber = [numbers objectAtIndex:0];
NSInteger valueOfFirstNumber = [firstNumber integerValue];
Sign up to request clarification or add additional context in comments.

Comments

0

you can't pull an NSInteger out of an NSMutableArray, basically because you can't put anything rather than objects in. in your case NSNumber would be the way to put numbers in NSMutablearray. if you do so you can easily get hold of your object, which is an NSNumber, and convert it to a NSInteger by:

NSMutableArray *array = [[NSMutableArray alloc] init];
// populate the array with NSNumbers
NSInteger number = [[array objectAtIndex:2] intValue];

1 Comment

right, sorry mate just edited the code it should be "intValue" instead of "integerValue". are you allocating and initializing the array?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.