使用NSInteger作为数组索引。

3

祝您新年快乐!

我遇到了以下问题。首先是逻辑:

从服务器获取JSON。JSON值始终为数字。将Plist读入数组中。使用来自服务器的JSON值作为索引打印带有数组的NSLog。

我的Plist:

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

我的代码:

获取Json

NSString *url_req=@"http://domain.com/index.php";

            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运作良好!

读取plist并log相应的值:

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

到目前为止,arrayNo[myLoc] 将返回 null,但是 arrayNo[1] 将返回 Atlanta。

我如何将 JSON 中的整数值用作数组索引?

谢谢!

编辑:使用 arrayNo[myLoc] 时出现错误输出

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

我的位置的值是多少?你在哪里声明它?它的类型是什么? - Hermann Klecker
1个回答

8
根据错误信息,您将myLoc声明为指向NSInteger的指针(NSInteger *myLoc),而不是实际的NSInteger(NSInteger myLoc)。应该使用后者。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接