iOS: HTTP service returning <null>, how to test for this? - ios

I have an app that relies on a web service that I have no control over. I'm currently trying to solve a bug.
In a particular case, an asynchronous HTTP request returns
"<null>"
When this happens I get an exception and my app crashes.
I've tried every method I can think of to test for this in an if statement including comparing various strings, arrays, and testing for the characters < and >. Essentially I want to break from a method if the value is found.
Has anyone run into this before, and how did you solve it?
Many thanks :)

Have you tried using the below code to test for it
if (myObject == [NSNull null]) {
// handle it
} else {
//
}
"The NSNull class defines a singleton object you use to represent null values in situations where nil is prohibited as a value (typically in a collection object such as an array or a dictionary)." - Apple

Ok, I figured it out. It must have helped to write the problem down. I hadn't created an IDENTICAL null object to compare it to yet. My null object actually was generated by a snippet of JSON code, so all i had to do was replicate such an object and use isEqual: to compare them.

Related

Getting a boolean value from a parse object and performing a if/else statement on it in Xcode 7, Swift 2

The title says it all. I have read through the Parse docs and it is just going right over my "new to coding" brain. How do I get a parse Boolean object, which i already have created, and perform a if/else statement on based on whether it is true or not?
Thank you
I use obj-c, not Swift, so I can't help you with syntax, but in iOS, you need to store/retrieve parse booleans as NSNumbers. So storing a boolean:
[myPFObject setObject:[NSNumber numberWithBool:myBool] forKey:#"myKey"];
for retrieving that object and using it as an if/else condition:
NSNumber *boolNumber = [myPFObject objectForKey:#"myKey"];
bool myBool = boolNumber.boolValue;
if( myBool )
...
Obviously, being able to do so depends on having properly saved / fetched your object from parse, which throws a lot of people off because it's synchronous, as in multi threaded. Say you call fetch on your object, then immediately try to access that bool value. You won't be able to, because the fetch happens on a separate thread, and your main thread immediately goes to the next line you try to access it. You need to be using the fetch/saveInBackgroundWithBlock methods of PFObjects, and doing whatever you need to do with the values inside of the callback, rather than outside.

NSMutableDictionary contents inconsistent with output of allValues

So long story short, there's a discrepancy between the output of a NSMutableDictionary's contents and the result of calling allValues on the same object. Below is some debugger output after inspecting the object which demonstrates my problem: (made generic of course)
(lldb) po self.someDict.allKeys
<__NSArrayI 0xa5a2e00>(
<SomeObject: 0xa5a2dc0>,
<SomeObject: 0xa5a2de0>
)
(lldb) po self.someDict.allValues
<__NSArrayI 0xa895ca0>(
0.5,
0.5
)
(lldb) po self.someDict
{
"<SomeObject: 0xa5a2dc0>" = (null);
"<SomeObject: 0xa5a2de0>" = (null);
}
So as we can see, the actual output of the NSMutableDictionary contains null values for both its entries, but the contents of .allValues contains the proper data. These three outputs were taken at the same time in execution.
I'm not sure why this is happening, but I think it may have something to do with the fact that I'm encoding/decoding the object which this dictionary is a property of using CoreData. I believe I'm doing this properly:
[aCoder encodeObject:self.someDict forKey:#"someDict"];
and to decode
self.someDict = [aDecoder decodeObjectForKey:#"someDict"];
The weird thing is that if I inspect the dictionary before it ever gets encoded, it is still in the state described at the beginning of the post, so this is why I'm doubtful the CoreData actions are screwing with the contents.
As always, please don't hesitate to request additional information.
EDIT: The problem was as answered below. I was using a custom class which didn't cooperate with isEqual, so my solution was to change the storage and structure of my logic, which made using a Dictionary unnecessary.
I have not been able to duplicate the problem using NSString as keys and NSNumber as values. I suspect that your custom class does not properly implement hash and/or isEqual. Specifically, the results from those two methods must be consistent, meaning that if isEqual returns true, then the hash values for the two objects must be identical.
You also need to ensure that your class implements NSCopying properly and that a copy is equal to the original.
As a general rule, don't use custom objects for dictionary keys. Just use strings and be done with it.
As user3386109 points out, custom objects must properly implement the -hash and -isEqual methods in order to be used as dictionary keys, and even then, custom objects don't work correctly for dictionary keys for things like key/value coding.

CoreData fault - how to get data

I've researched tons of questions and documents about CoreData returning faults instead of actual values:
Relationship 'whiskers' fault on managed object (0xb7abab0)
This happens when I'm trying to get the count for the number of whiskers, such as:
self.numWhiskersLabel.text = [NSString stringWithFormat:#"%d", cat.whiskers.count];
Even if I try to log the whiskers set directly I still get a fault:
NSLog(#"whiskers: %#", cat.whiskers);
I understand that "Core data will not return full object until there is a need to access the actual value of that object. Each of your returned objects will be a 'fault' until this point." That's great, but there is a need to access the actual value at this point. I need the value right now! So how do I get out of this oxymoron? How can accessing the count of a Set not be considered needing the value?
I didn't get any feedback from my comment so I'm just going to assume whiskers is a set of NSManagedObjects
The set wont be loaded initially because internally it's coming from another table in the db. When you access .whiskers.count it still doesn't need to go and get the data yet, because all you're wanting is the number of whiskers in the set.
When you pull a whisker out of the set, then it will be faulted, try doing
NSLog(#"whiskers: %#", [cat.whiskers.anyObject anyProperty]);
That should give you a loaded NSManagedObject.
This is an error condition. Something is wrong with that NSManagedObject instance. Either it was deleted before you accessed it or you are trying to touch it from the wrong thread.
Please edit your question and show the code that is accessing that NSManagedObject.
Also, what happens when, in the debugger, you just do a po cat? Do you see the full Cat object or is that giving a fault error as well?

How to safely treat data from JSON when the expected type may differ?

As of iOS 5 and OSX 10.7 and higher it is really easy to parse JSON with NSJSONSerialization, which will return either an NSDictionary or NSArray (or mutable variants, if specified) when parsing JSON. Values are parsed as common Cocoa types such as NSString and NSNumber however I would be interested to know how careful I need to be when taking the data from the NSDictionary or NSArray and parsing it into data objects in my app. My key concerns are whether the key's value a) is not nil and b) isn't of an unexpected type.
For example, assume I had the following JSON object:
{
"version":1,
"title":"Some interesting title",
"info":"Some detail here"
}
Currently, this would be parsed as an NSDictionary:
#{
#"version": #1,
#"title":#"Some interesting title",
#"info": #"Some detail here"
}
My problem is how careful I should be when checking the data types of what I'm getting back. In theory, if I'm using a good API I should always get a numeric value for the version key, but what if for some reason it is changed server side to the following:
{ "version:"1", ... }
Or even worse:
{ "version:"one", ... }
If I attempt the following code, I will get hit an exception and my app would crash:
NSNumber * myNumber = dictionary[#"version"];
if ([myNumber isEqualToNumber:#1])
{
...
}
The code wouldn't execute because a) dictionary[#"version"] would be an NSString and b) isEqualToNumber: is only available on NSNumber (unrecognized selector exception, app would crash).
Equally, problems could arise if the JSON for "info" was changed to the following:
{
"info":{
"code":200,
"message":"Some detail here"
}
}
If my app expects an NSString for the key info it will again crash, because an NSDictionary will have been found instead.
On the large part, most JSON from an API or file should be sound and supported by the current version of the app and one would hope that all JSON is versioned and correctly encoded server side. In some cases, if the JSON has been corrupted or modified, the app could crash, which I want to avoid.
Potential solutions:
Check every single key/value pair for isKindOfClass: or respondsToSelector: and only continue if true
Check the key exists and produce an error if nil
Wrap up everything in a try/catch block, however I would rather what can be used is used and an error is produced if something is wrong with the data. This could end up with a lot of #try/#catch statements inside one another
Each of these solutions is rather bulky and adds a lot to my code which I would prefer to avoid, if possible (and when working with 'good' JSON it is perfectly possible). If there is an alternative solution that will handle the process of parsing JSON, checking keys' type and values before putting it in a custom object I would love to know.
You should generally be running against a stable API. The kind of changes you're worried about should be accompanied by a version number change in any reasonable system which would insulate your app from the change until an appropriate upgrade time. So, you should generally know the data type to expect.
In some cases the API will specify that a dictionary or an array may be received depending on the multiplicity, something like that. In this case you should check the class and act accordingly.
You should definitely check for nil and NSNull and handle those gracefully.
Corrupted JSON should be handled by the parser and an appropriate error returned to you.
Also, you could use a framework like RestKit to do the mapping to your custom objects for you. It does a lot of data type checking as standard and removes basically all of your mapping code into a simple configuration. It also handles all of the network comms (via AFNetworking).
You need to make sure your code is safe against attacks from hackers. When you request JSON from a server, you must expect that the data doesn't come from your server but from somewhere else, and that someone else might have designed the data returned to cause maximum damage. Now just crashing if you receive a string instead of a number is quite secure.
You must expect that your request to the server is instead fulfilled by some brain damaged hardware that tries to be "helpful" for example when an internet connection fails. Instead of JSON you might receive a "helpful" website that is supposed to tell a user how to reset their router. A user trying to use someone's free WiFi may have connections return weird result. That's usually no problem with JSON because the parsing will fail (so failed parsing is something you should expect and handle), more of a problem if you expect html.
You must expect that a public API that you are using has bugs or unexpected behaviour and you should behave well when that happens. Add debugging code that will at least log anything unexpected while you are developing. Write your code so that it works with any behaviour that the API shows.
If you are using your own API, you should also log anything unexpected, and then tell the server people if they do anything they shouldn't.

Sorting a NSSet of NSManagedObjects by a NSDate yields error

I am trying to pull in a RSS feed and sort by pubDate. When I examine the 'updated' property, most of the time it is correct and give me a proper date but when I try to convert from a set to a sorted array, I get random results from the sort. I've tracked this down to the fact that when sort is doing it's comparesion, the property (which is an NSDate, see figure1) is coming in and being compared as a __nscfnumber! (also figure2)
Any help or idea would be much appreciated.
figure1
figure2
I assume the comparator block is just for diagnostic purposes? You don't actually need to supply a comparator for NSDate or any of the provided attribute type classes.
If the debugger is reporting that the date1 object is of a NSNumber-cluster class type, then somewhere a NSCFNumber instance is being assigned to to the updated attribute. The debugger ignores factors like a cast and instead simply asked the object what its class is. If the object says it is a NSCFNumber then it is, regardless of how the code treats it otherwise.
Why that happens, I can't say based on the code provided.
You might try logging the value and class of the updated attribute before you attempt the sort to see if it reports properly. I would also recommend decomposing the entire line. Nesting all those method calls will work of course but it is error prone and hard to debug.

Resources