Cocoa JSON - Check whether array or dictionary - cocoa

I am using the Cocoa JSON framework ( http://code.google.com/p/json-framework/ ) to communicate with an API.
The problem is that the API returns a dictionary if there is an error but returns an array of the results if it works.
Is there a good way to detect if the JSONValue is an array or a dictionary?
Thanks.

You can use isKindOfClass: to test whether the object is an instance of NSDictionary or of any subclass thereof.
In most circumstances, you would be better served by a respondsToSelector: check, but this is one case where you really are better off testing its class membership.
Of course, you can test whether it's an array instead of whether it's a dictionary; as long as the API you're using only returns an array or dictionary, the effect is the same.
For true robustness, test both array and dictionary membership, and throw an exception or present an error if the object is neither.

Maybe try to check length property.
if (jsonObj.length) {
//doSomeWork
}

Try this:
if ([YourData isKindOfClass:[NSArray class]])
{
NSLog(#"Array format found");
}
else
{
NSLog(#"Dictionary format found");
}

Related

Hash method get on ruby

I need to get some values for a hash but, I don't know how can I do it!
My data:
data = {
name: "Pedro Álvares",
age: 35,
sensitive_data: {
cpf_cnpj=>27046645678,
fantasy_name: "I have the power"
}
}
I search for ruby methods and find the method values_at, but this method gets only the first_data like name, age.
If I use:
name = data.values_at(:name)
the field returned is Pedro Álvares
but if I try use:
fantasy_name = data.values_at(:fantasy_name)
the data returned is nil.
How can I get the field without using data[:sensitive_data][:fantasy_name]?
Because you know the correct structure of the hash you should write:
data[:sensitive_data][:fantasy_name]
#=> "I have the power"
You should not use dig here. Why? Suppose you accidently wrote
data.dig(:sesnitive_data, :fantasy_name)
The would return nil (because data has no key :sesnitive). Depending on the context the error might not surface until sometime later, making debugging more difficult than is necessary.
By contrast, if you wrote
data[:sesnitive_data][:fantasy_name]
data[:sesnitive_data] would return nil (because data has no key :sesnitive_data) and then nil[:sesnitive_data] would raise an exception, informing you that nil has no method []. That is precisely what you want to happen: you want to be notified of the error immediately, and have the reason for it it pinpointed, so you can easily correct your code.
Hash#dig, Array#dig and Struct#dig (which call each other) have their uses (when you do not know the structures of objects in advance--a hash's keys, for example), but those methods should not be used when an object's structure is known.
You could get the nested value by dig method:
data.dig(:sensitive_data, :fantasy_name) # => "I have the power"

How do I remove all map annotations in swift 2

I had working code to remove all map annotations with a button, but after my update to xcode 7 I am running into the error:
Type 'MKAnnotation' does not conform to protocol 'SequenceType'
if let annotations = (self.mapView.annotations as? MKAnnotation){
for _annotation in annotations {
if let annotation = _annotation as? MKAnnotation {
self.mapView.removeAnnotation(annotation)
}
}
}
In Swift 2 annotations is declared as non optional array [MKAnnotation] so you can easily write
let allAnnotations = self.mapView.annotations
self.mapView.removeAnnotations(allAnnotations)
without any type casting.
self.mapView.removeAnnotations(self.mapView.annotations)
If you don't want remove user location.
self.mapView.annotations.forEach {
if !($0 is MKUserLocation) {
self.mapView.removeAnnotation($0)
}
}
Note: Objective-C now have generics, it is no longer necessary cast the elements of 'annotations' array.
SWIFT 5
If you don't want to remove user location mark:
let annotations = mapView.annotations.filter({ !($0 is MKUserLocation) })
mapView.removeAnnotations(annotations)
The issue is that there are two methods. One is removeAnnotation which takes an MKAnnotation object, and the other is removeAnnotations which takes an array of MKAnnotations, note the "s" at the end of one and not the other. Attempting to cast from [MKAnnotation], an array to MKAnnotation a single object or visa versa will crash the program. The line of code self.mapView.annotations creates an array. Thus, if you are using the method removeAnnotation, you need to index the array for a single object within the array, as seen below:
let previousAnnotations = self.mapView.annotations
if !previousAnnotations.isEmpty{
self.mapView.removeAnnotation(previousAnnotations[0])
}
Thus, you can remove various annotations while keeping the users location. You should always test your array before attempting to remove objects from it, else there is the possibly getting an out of bounds or nil error.
Note: using the method removeAnnotations (with an s)removes all annotations.
If you are getting a nil, that implies that you have an empty array. You can verify that by adding an else statement after the if, like so;
else{print("empty array")}

Collection Object operator for #firstObject Key-value coding KVC

I'm often required to retrieve the 1st object belonging to a Set. (Using that object as a representative of that set.)
I envision a Collection Object operator, akin to the
#unionOfObjects
BUT clearly
#firstObject
Is it possible to create such a Collection operator!
Currently there's no way to define custom collection operators. However, due to some internal magic there is a funny solution:
NSSet *testSet = [NSSet setWithArray:#[#"one", #(1)]];
id object = [testSet valueForKey:#"#anyObject"];
NSLog(#"anyObject (%#): %#", NSStringFromClass([object class]), object);
UPD: Forgot to mention another handy trick: you can use #lastObject on NSArray!

Returning multiple values from a method

I have a method drive that goes like this:
public double drive(double milesTraveled, double gasUsed)
{
gasInTank -= gasUsed;
return totalMiles += milesTraveled;
}
I know I can't return multiple values from a method, but that's kind of what I need to do because I need both of these values in my main method, and as it is now it's obviously only returning the one. I can't think of anything that would work. Sorry if this is a super beginner question. What can I do to get both values to return from the method?
You can return multiple value from a function. To do this You can use structure.
In the structure you can keep required field and can return structure variable after operation.
You can also make a class for the required field if You are using OOPS supporting language but Structure is best way.
In most languages you can only return a single value from a method. That single value could be a complex type, such as a struct, array or object.
Some languages also allow you to define output parameters or pass in pointers or references to outside storage locations. These kinds of parameters also allow you to return additional values from your method.
not sure, but can you take array of your values?
array[0]=gasInTank;
array[0] -= gasUsed;
array[1]=milesTraveled;
array[1] -= milesTraveled;
return array;

ViewBag- MVC3-ASP.NET

I am tring to assign a value to ViewBag in the controller for later usage in the View, It complaines with the following error.
Assigning the value in the Controller like this.
ViewBag["isAdmin"]=true;
Error:
Cannot apply indexing with [] to an expression of type 'System.Dynamic.DynamicObject'
Does anyone had this before?
All you need is ViewBag.isAdmin = true. the you can access is with
if(ViewBag.isAdmin)
{
//do stuff
}
As a follow-up, the idea behind ViewBag (and ViewData) is that you can store off key-value pairs of stuff and conveniently access them over in the View.
With ViewData, you reference these things like so:
ViewData["SomeKey"] = someObject;
If you want to do the same using the ViewBag instead (which provides a wrapping around that ViewData dictionary construct and makes it a little less verbose and a bit more readable) you reference things like so:
ViewBag.isAdmin = true;
and can check them, as tyrongower stated above, like so:
if (ViewBag.isAdmin)
{
// do stuff
}
I typically use the ViewBag syntax when I do use this construct, but they really do reference the same stuff. So if you did something like so outside the View:
ViewData["isAdmin"] = true;
you could reference it like this, if you were so inclined:
ViewBag.isAdmin
or vice-versa.
Just a little more detail on the concept.

Resources