简体   繁体   English

从JSON响应对象获取价值

[英]Get value from JSON response Object

I am making a JSON request and want to get an int value from one of the fields. 我正在发出JSON请求,并希望从其中一个字段获取int值。

{
"currentPage": 1,
"numberOfPages": 5,
"totalResults": 234,
"data": [],
"status": "success"
}

I want to get the value of numberOfPages. 我想获取numberOfPages的值。 My code is as follows 我的代码如下

_pages = [responseObject objectForKey:@"numberOfPages"];
_numberOfPages = (int)_pages;
NSLog(@"%d", _numberOfPages);

Instead of the value for numberOfPages, the NSLog is 150198512. Can somebody please explain why? 而不是numberOfPages的值,NSLog是150198512。有人可以解释为什么吗? Trying object at index 0 causes it to crash. 尝试索引0处的对象将使其崩溃。

_pages should be an NSNumber in your definition. _pages应该是您定义中的NSNumber You can't cast that to get a primitive type, you have to request the primitive type. 您不能将其强制转换为获取原始类型,而必须请求原始类型。 _numberOfPages should be an NSInteger (or perhaps NSUInteger ) and you should get the value with: _numberOfPages应该是NSInteger (或者可能是NSUInteger ),并且您应该使用以下方法获取值:

_numberOfPages = [_pages integerValue];

Aside: consider using self.pages and self.numberOfPages rather than accessing the instance variables directly (it could help you with maintenance in the future). 另外:考虑使用self.pagesself.numberOfPages而不是直接访问实例变量(这可能会在将来帮助您进行维护)。

Using self.pages results in a call to the pages (or self.pages = xxx in a call to setPages:xxx ) method to get (or set) the content of the instance variable ( _pages ). 使用self.pages到调用结果pages (或self.pages = xxx在调用setPages:xxx )方法来获取(或设置)的实例变量(内容_pages )。 So, if you have a custom implementation of that method it will be called and your custom logic will run. 因此,如果您具有该方法的自定义实现,它将被调用,并且您的自定义逻辑将运行。 If you just use _pages then it won't be called and you will need to do a lot of editing later if you need to make a change. 如果仅使用_pages ,则不会调用它,如果需要进行更改,则以后需要进行大量编辑。

Your best option is to use self.XXX = xxx whenever you want to update a property and XXX xxx = self.xxx when you want to use it. 最好的选择是,每当要更新属性时都使用self.XXX = xxx而要使用它时则使用XXX xxx = self.xxx

This isn't a hard and fast rule. 这不是一个硬性规定。 Interesting discussion here . 这里有趣的讨论

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM