Use NSInteger as array index



Have a happy year!

I am having trouble with the following. First logic:

Get json from server. Json value is always a number. Read plist into array. NSLog the array with index of the json value from server.

My plist:

Key     Type     Value
Item 0  String   New York
Item 1  String   Atlanta

My code:

Get Json

NSString *url_req=@"";

            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url_req]];

            NSData *response = [NSURLConnection sendSynchronousRequest:request
                                                     returningResponse:nil error:nil];

            NSError *jsonParsingError = nil;
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response
                                                                      options:0 error:&jsonParsingError];

            NSArray *cityArray = [json objectForKey:@"city"];
            for (NSDictionary *alert in pestoArray ){
                myLoc = [[alert objectForKey:@"location"] integerValue];

Json is working just fine!

Read plist and nslog the corresponding value:

NSString *path = [[NSBundle mainBundle] pathForResource:@"townsList" ofType:@"plist"];
 NSArray *arrayNo= [[NSArray alloc] initWithContentsOfFile:path];            
 NSLog(@"City %@",arrayNo[myLoc]);

So far arrayNo[myLoc] will return null but arrayNo[1] will return Atlanta.

How can i use the integer value from JSON as an array index?

Thank you!

EDIT: Error output when using arrayNo[myLoc] is

Indexing expression is invalid because subscript type 'NSInteger *' (aka 'int *') is not an integral or Objective-C pointer type





According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.


Facebook Comments

Post a comment