I am making a JSON request and want to get an int value from one of the fields.
{
"currentPage": 1,
"numberOfPages": 5,
"totalResults": 234,
"data": [],
"status": "success"
}
I want to get the value of 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? Trying object at index 0 causes it to crash.
_pages
should be an NSNumber
in your definition. 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 = [_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).
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
). 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.
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.
This isn't a hard and fast rule. Interesting discussion here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.