How to convert a list to NSArray? - ios

I keep getting this list which is stored as NSString:
(
"one",
two,
"three",
4
)
How do I convert the values into NSArray?

If you provide more information about where this list comes from or how it's made, maybe i can be of more help.
Otherwise, you can convert your string in an array of strings by "splitting" when the , appears, like so :
Your initial string is saved as myString
You should first remove then ( & ) at the start and the end of your string, and then do this :
NSArray* foo = [myString componentsSeparatedByString:#","];
And foo now contains these values :
"one"
two
"three"
4
But I still think you should give a little more information as i said at the start of this answer, because I have a feeling this is not exactly what you're looking for.
EDIT : as I said in comments, because it's a JSON, simply get the results into a dictionary, and then do :
NSArray *array = [results objectForKey:#"blocks"];

If your JSON is in this form, convert your JSON response in a dictionary and simply get the value of keyword "blocks" in an array. For example if you have
NSDictionary *dict = {"blocks": ["one", two, "three",4]};
The following will be your array
NSArray *array = [dict valueForKey:#"blocks"];

Related

Concatenate Strings for Dictionary:syntax error

The following code to conditionally concatenate strings for a dictionary seems to work up to the point where I try to place the concatenated result in the dictionary. Can anyone see the error?
NSDictionary *jsonDictionary;
NSString* dictString = #"#\"first\":first,#\"last"
NSString *dictString2=dictString;
if (date.length>0&&![date isKindOfClass:[NSNull class]]) {
//only include this key value pair if the value is not missing
dictString2 = [NSString stringWithFormat:#"%#%s", dictString, "#\"date\":date"];
}
jsonDictionary = #{dictString2}; //syntax error. Says expected colon but that does not fix anything
The syntax for creating an NSDictionary using object literals is:
dictionary = #{key:value}
(and optionally, it can contain multiple key/value pairs separated by commas, but never mind that right now.)
Where "key" and "value" are both NSObjects.
Your line that is throwing the error only contains 1 thing. The contents of a the string in dictString2 has nothing to do with it.
It looks to me like you are trying to build a JSON string manually. Don't do that. Use NSJSONSerialization. That class has a method dataWithJSONObject that takes an NSObject as input and returns NSData containing the JSON string. That's how you should be creating JSON output.
Creating an NSDictionary with values that may be null:
NSDictionary *dict = #{
#"key" : value ?: [NSNull null],
};
When serializing a dictionary, NSNulls are translated to null in the JSON.
If you want to exclude such keys completely, instead of having them with a null value, you'll have to do more work. The simplest is to use an NSMutableDictionary and test each value before adding it.

Dictionary key-value using with array

I have an array and it has lots of dictionary's keys it comes from API. My array as follows
Dictionary keys array :
NSArray *arr = #[#"01", #"02", #"03"];
Dictionary with key-value pairs
NSDictionary *dic = #{#"01": #"Hero", #"02" : #"Enemy", #"03" : #"Boss"};
Basically i want to match array values corresponding to dictonary keys without using array. I found a solition about that but I don't want to use for-loop for every cell(I have a lots of cell). My solution is like that
for(NSString *item in arr) {
[convertedArr addObject:[dic valueForKey:item]];
}
NSLog(#"%#", [convertedArr componentsJoinedByString:#","]);
Asumme have an array like this (1,2,3) and dictionary looks like {1 = "a", 2 = "b", 3 = "c"} I just want to give an array and it should return dictionary values like this ("a","b","c")
Anybody should give me better approach without using array? Thanks.
You can replace your for-loop by
NSArray *convertedArr = [dic objectsForKeys:arr notFoundMarker:#""];
which is at least less code. (The notFoundMarker: is added for all keys
in the array which are not present in the dictionary. Your code would crash
in that situation.)
It might perform slightly better because it is a library
function. But I doubt that the difference is big, because in any case a dictionary
loopup is required for all keys in arr.

Sort array based on second array order

I have an array from a plist and each value contains an key and a string and a secondary array that I get from a json file online. I want to order the secondary array based on the keys in the first array.
I want to achieve something like this:
array1:
Item0 - EUR
- String
Item1 - USD
- String
Item2 - AUD
- String
etc
array2:
Item0 - AUD
- 123.242
Item1 - EUR
- 535.123
Item2 - USD
- 325.646
etc
I have the same key index on both but I want to get the value for the key index from array2 based on the order of the key index in array1.
I have researched online but I cannot find a suitable solution that I can understand how to implement it.
How can I implement this?
Here is the plist file - https://gist.github.com/iulianvarzaru/11c400ba1edf4a165082
And the json file - https://gist.github.com/iulianvarzaru/1915e02a9201c57f49b3
Given that the JSON file you've linked to doesn't contain an array but a dictionary, you can simply iterate over array1 from the plist file. Each element of that array is a dictionary with a "Cod" key and a "Descriere" key. Get the value for the "Cod" key and then simply use that value as the key into the dictionary from the JSON file.
NSDictionary* jsonFileDict = ...;
NSDictionary* jsonFileInnerDict = jsonFileDict[#"rate"];
for (NSDictionary* dict in array1)
{
NSString* code = dict[#"Cod"];
NSNumber* jsonNumber = jsonFileInnerDict[code];
// Do something with jsonNumber
}
It sounds like these are key-value pairs, in which case, you can convert it to a Map, and then do direct lookups.
If you can manipulate the JSON file as JSON, then it reduces a conversion, but may not be the most efficient implementation.
Caveats:
This method assumes that you wont have key overloading (which is possible in a numeric array, but not in a map)
This requires a conversion from one data structure to another
EDIT: (due to increased information by OP).
The JSON file you receive doesn't contain an array, it contains an object. Thus, all the values are direct-lookup. So, you can traverse your array in Obj-c, and directly access the corresponding values in the JSON.
Sorry about the lack of actual code-samples.
You are dealing with a dictionary in the response, not an array.
You should transform it to something like
{
#"currency": #"EUR",
#"value": 123.45
}
create and sort it it like
NSArray *keys = #[#"EUR",#"USD",#"AUD"];
NSDictionary *dict = #{#"AUD":#(123.242), #"EUR": #(535.123), #"USD": #(325.646)};
NSMutableArray *result = [#[] mutableCopy];
for (NSString *key in keys) {
[result addObject:#{#"value":dict[key], #"currency": key}];
}
NSLog(#"%#", result);
(
{
currency = EUR;
value = "535.123";
},
{
currency = USD;
value = "325.646";
},
{
currency = AUD;
value = "123.242";
}
)
Or write a model class that can handle this information.

Why does iOS look at the following as a NSDictionary and not an array?

{
"success":true,
"listings":
{
"50831582253b4acf09000000":
{
"id":"50831582253b4acf09000000",
"title":"fddfds",
"assets":[],
"discussions":[]
}
},
"displaymessage":"1 Listings Found"
}
I am still struggling between dictionaries and arrays. What would make the above an Array?
Thanks
There's a pretty big difference between dictionaries and arrays. Dictionaries store data entries in relation to a keys you specify on instantiation. For example:
NSDictionary *myDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:#"object1",#"key1",#"object2",#"key2", nil];
This alloc/inits a dictionary and sets "object1" for "key1" and "object2" for "key2", so then if you wanted to ask for the value of "key1" you could access it with the following.
NSLog(#"%#",[myDictionary objectForKey:#"key1"]);
Objects in a dictionary can be arrays, dictionaries, booleans, data, dates, numbers and strings.
On the other hand, arrays store data by the datas index within the array:
NSArray *myArray = [[NSArray alloc] initWithObjects:#"object1",#"object2",#"object3", nil];
You can then access the a specific bit of data from within the array by asking for objectAtIndex:, ex:
NSLog(#"%#",[myArray objectAtIndex:1]);
Which will return "object2" because the first index in an array is always "0".
Check the JSON docs
JSON Arrays are represented by square brackets
[ "object1", "object2" ]
JSON arrays are normally represented in Objective-C by NSArray. This matches up with the new literal syntax
#[ #"object1", #"object2" ]
JSON Objects are represented by curly brackets
{ "key" : "value" }
JSON objects are normally represented in Objective-C by NSDictionary. This also matches up with the new literal syntax
#{ #"key" : #"value" }
As you can probably tell, the entities or "cells" in the list are separated by commas (,)
In a serialized dictionary, an entity is broken into a key:value pair by a colon (:)
"success":true
Where the first part in quotes before the colon is the key, and the second part is the value that corresponds to that key.
A serialized array might look something like this:
{"hello", "goodbye", "world", "words", "friendship"}
Notice that entities are still separated by commas, but there are no colons outside of quotes.
Another key difference is that in dictionaries, keys must be unique, so you shouldn't have something like this:
{"success":true, ..., "success":false}
whereas in an array, elements do not have to be unique:
{"hello", "hello", "goodbye"}
Hope this helps =)

appending strings to NSMutableArray in NSMutableDictionary

I need to append strings to an array kept inside of a dictionary each time a word matches a pattern of another word. The second line below (setObject) overwrites instead of appending.
The end result should be arrays in a dictionary where the the key(pattern) identifies many strings that fit that pattern.
NSMutableDictionary *eqClasses = [[NSMutableDictionary alloc] init];
[eqClasses setObject:tempWordStr forKey:wordPattern];
Is there an easy way to append?
Try this:
NSMutableArray* array = [eqClasses objectForKey:wordPattern];
if(!array) {
// create new array and add to dictionary if wordPattern not found
array = [NSMutableArray array];
[eqClasses setObject:array forKey:wordPattern];
}
[array addObject:tempWordStr];
You indicate that the values in the dictionary should be arrays, but it looks to me like eqClasses contains NSStrings (tempWordStr). Don't you need to create an NSArray to hold the NSStrings associated with a keyword and then make the array the value in the dictionary that corresponds to the keyword? If the dictionary already contains the key, you need to retrieve the array associated with the key, add the new string to the array, and then call setObject using the array with the key.

Resources