Snowman
Snowman

Reputation: 32071

Simple NSInteger and NSMutableArray question

I'm trying to access an array using another array integer value as an index.

 NSInteger index=[appDelegate.randomRiddles objectAtIndex:appDelegate.randomRiddlesCounter];
 int i = index;
 questionText.text = [[appDelegate.currentRiddlesContent objectAtIndex:i] objectForKey:@"question"];

//where appDelegate.randomRiddlesCounter is an NSInteger and appDelegate.randomRiddles is a NSMutableArray

However I'm getting incompatible pointer to int conversion warning. How can I fix this above code? The warning I get is coming from the first line.

Upvotes: 2

Views: 1213

Answers (3)

Wizz
Wizz

Reputation: 1267

An NSArray like object can only store Objective-C object pointers (i.e. everything that you can assign to an id)

With objectAtIndex you get the object, with indexOfObject:(id)anObject you get the corresponding index.

These two instructions are both valid:

id bla = [appDelegate.randomRiddles objectAtIndex:appDelegate.randomRiddlesCounter];
NSInteger index = [appDelegate.randomRiddles indexOfObject:myObject];

The second assumes that myObject is at least of type id So you try to convert a pointer to an int. Therefore the warning is issued.

Upvotes: 0

Rudy Velthuis
Rudy Velthuis

Reputation: 28806

Try:

NSNumber *index = [appDelegate.randomRiddles objectAtIndex: appDelegate.randomRiddlesCounter];
int i = [index intValue];
questionText.text = [[appDelegate.currentRiddlesContent objectAtIndex: i] objectForKey: @"question"];

NSInteger is an integral type, not an object.

Upvotes: 2

ColdLogic
ColdLogic

Reputation: 7275

Try this:

int i = [index intValue];

Upvotes: 0

Related Questions