ios-save nsdictionary in nsuserdefault - ios

i want to save a nsdictionary have value null in nsuserdefault and don't need replace and delete value null
How?
My code -> impossible save in nsuserdefault
NSMutableArray * _itemsNames;
NSString * itemsFilename;
- (void) responseArray:(NSMutableArray *)array {
[_itemsNames setArray:array];
[spinner stopAnimating];
[_itemsNames writeToFile:itemsFilename atomically:YES];
NSMutableSet *filepathsSet = [[NSUserDefaults standardUserDefaults] objectForKey:#"test"];
[filepathsSet setByAddingObject:itemsFilename];
[[NSUserDefaults standardUserDefaults] setObject:filepathsSet forKey:#"test"];
}
The json is:(have value null)
({
ID:11,
name:21-12-2012,
des:"<null>",
url:
[
{
ID:1,
name: "<null>"
},
{
ID:2,
name:"<null>"
}
]
},
{
ID:12,
name:if i die young,
des:"<null>",
url:
[
{
ID:3,
name: "<null>"
},
{
ID:21,
name:"<null>"
}
]
})

If you have dictionary myDict
Then
[[NSUserDefaults standardUserDefaults] setObject:myDict forKey:#"MyDictionary"];
myDict will be saved only if it contains all objects that implements NSCoding
Regarding your null concept.
There is no need to save nil values in dictionary for a key.
If you try to get an object for a key and in dictionary there isn't any object related to that key then it will return nil. So no need to save null values

If you really need to store null values in NSDictionary use NSNull. Anyway you can just not store key with null value and then for [mydict objectForKey:#"keyWithNullValue"] you'll get nil.
But as I said if you really really want to store null use something like that:
NSSet *mySet = [NSSet setWithObjects:#{
#"ID":#(11),
#"name":#"21-12-2012",
#"des":[NSNull null],
#"url": #[#{
#"ID":#(1),
#"name": [NSNull null]
}, #{
#"ID":#(2),
#"name":[NSNull null]
}]
},#{
#"ID":#(12),
#"name":#"if i die young",
#"des":[NSNull null],
#"url": #[#{
#"ID":#(3),
#"name": [NSNull null]
}, #{
#"ID":#(21),
#"name":[NSNull null]
}]}, nil];

You mention saving dictionaries, but all you are showing is the JSON representation of an array of dictionaries.
You don't need to do anything strange, take the returned JSON data and turn it into an array and write the array to a plist. Turning it into a string and then trying to make a collection out of it is probably causing you the problems.

Related

Objective-c NSMutableDictionary set with an array keep empty

I'm new here, but I use to read this site when I need something, but today, I can't find an answer to my question.
I'll try to explain my problem with enough details.
I need to add an array into a NSMutableDictionary at a specific key. The key added into it is correctly up, but my dictionary value keep empty. Here is my code :
dictionarySection = [[NSMutableDictionary alloc] initWithObjects:arraySectionValues forKeys:arraySectionKeys];
dictionaryClip = [[NSMutableDictionary alloc] initWithCapacity:[arraySectionKeys count]];
NSArray *tabSection = [dictionarySection allKeys];
id key,value;
for (int j=0; j<tabSection.count; j++)
{
array = [NSMutableArray array];
key = [tabSection objectAtIndex: j];
value = [dictionarySection objectForKey: key];
//NSLog (#"Key: %# for value: %#", key, value);
for (SMXMLElement *clip in [books childrenNamed:#"clip"]) {
if([[clip valueWithPath:#"categorie"] isEqualToString:value]){
[array addObject:[clip valueWithPath:#"titre"]];
}
}
NSLog(#"Test array %#",array);
[dictionaryClip setObject:array forKey:key];
[array removeAllObjects];
NSLog(#"Test dictionary %#",dictionaryClip);
}
Here the NSLog result :
2015-07-15 14:34:48.272 test[15533:390301] Test array (
"CDS : ITV Philippe Dunoyer",
"FLASH INFO NCI : crise des banques",
"Les Roussettes sont-elles dangereuses ?",
"Flash infos banques gr\U00e8ve",
"CDS : ITV Paul Langevin",
"CDS : ITV Valls",
"CDS : ITV Victor Tutugoro",
"CDS : ITV Roch Wamytan",
"NCGLAN 20",
"Flash Info : dispositif anti-d\U00e9linquance"
)
2015-07-15 14:34:48.273 test[15533:390301] key : 0
2015-07-15 14:34:48.273 test[15533:390301] Test dictionary {
0 = (
);
}
As we can see, the array is filled, the dictionary's key is correct, but the array isn't into my dictionary.
How may I suppose to fill my dictionary with this array?
Thanks a lot guy(s) for answer(s) :)
Ps : excuse my english :(
You are calling removeAllObjects: method for same instance of array which you are passing in dictionary so it objects are being removed in stored array. Try to pass that array's copy or a new instance of array with same objects.
Example:
[dictionaryClip setObject:[array copy] forKey:key];
In Objective-C arrays are reference types.
The method setObject:forKey: puts a pointer to the array into the dictionary, the array is not copied.
If you remove all objects from the array, they also disappear in the dictionary

Combining several JSON objects into one

I need to put an array of JSON objects into a new JSON object.
{“megaObject”:[
{ “key”:8,
“key2”:”val”
},
{ “key”:5,
“key2”:”val”
},
{ “key”:6,
“key2”:”val”
}
]
}
I have created the array like this:
NSArray *myArray = #[NSData json1, NSData json2, NSData json3];
Is this the correct way to make a JSON array and if so, how can I put it as a value to key `megaObject.'
I'm new to iOS development so any help is great.
If you represent the JSON object as a NSDictionary, you can simply use the methods of this. I.e.
NSDictionary *jsonDict1;
NSDictionary *jsonDict2;
NSDictionary *jsonDict3;
NSArray *resultAry = #[jsonDict1, jsonDict2, jsonDict3];
NSDictionary *resultDict = #{#"megaObject" : resultAry};
and from here on convert to NSData or anything else you need ;) First understand what classes you are working with and then look at their methods in the API. Investigate more and concentrate your questions on things that you couldn't solve after at least 2 hours investigation ;)
UPDATE
taking a look at your structure...
{"megaObject": // <-- NSDictionary "resultDict" with the key "megaObject" and NSArray "resultAry" with 3 NSDictionaries as value.
[
{ // NSDictionary "jsonDict1" with 2 entries.
“key”:8,
“key2”:”val”
},
{ “key”:5, // and so on
“key2”:”val”
},
{ “key”:6,
“key2”:”val”
}
]
}
I would use NSJSONSerialization, from the documentation:
You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.
Not sure what you want to reach as result, but this example can help you undersand how to assign an array as value into a NSDictionary as key.
NSDictionary *NEWjSON= [[NSDictionary alloc]init];
NSArray *myArray = #[
#{
#"key" : #"8",
#"key2" : #"val",
},
#{ #"key" : #"5",
#"key2":#"val",
},
#{ #"key":#"6",
#"key2":#"val"
}
];
[NEWjSON setValue:myArray forKey:#"megaObject"];

Converting a Dictionary with a value of [NSNull null] to JSON

I am trying to use this code:
NSDictionary *innerMessage
= #{#"nonce":[NSNumber numberWithInteger:nonce],
#"payload":#{#"login": [NSNull null]}};
NSError * err;
NSData * innerMessageData = [NSJSONSerialization
dataWithJSONObject:innerMessage options:0
error:&err];
to create a JSON object with the following structure:
{
"apikey": "e418f5b4a15608b78185540ef583b9fc",
"signature": "FN6/9dnMfLh3wZj+cAFr82HcSvmwuniMQqUlRxSQ9WxRqFpYrjY2xlvDzLC5+qSZAHts8R7KR7HbjiI3SzVxHg==",
"message":{
"nonce": 12,
"payload": {
"Login": {}
}
}
}
However, this is the actual result which I get:
{"nonce":1398350092512,"payload":{"login":null}}
Why is [NSNull null] in my dictionary not being converted to {}?
How would I need to change my code to get the correct JSON
structure?
Thank you!
NSNull is suppose to become null in the JSON.
If you want an empty dictionary in the JSON ({}) you should use an empty dictionary - #{}.
Change code to
NSDictionary *innerMessage = #{
#"nonce":#12,
#"payload":#{#"login": #{}}
};
NSError * err;
NSData * innerMessageData = [NSJSONSerialization
dataWithJSONObject:innerMessage options:0
error:&err];
This will create the desired response
{
nonce = 12,
payload = {
login = {}
},
}
null is a perfectly valid JSON value; what were you expecting? How should NSJSONSerialization know that you wanted [NSNull null] to be converted to an empty object? (For that matter, why wouldn’t nulls be converted to an empty array, an empty list, or numeric zero?)
The solution is to process your innerMessage before you serialize it, replacing any instances of [NSNull null] with #{} (or, equivalently, [NSDictionary dictionary]).

Xcode - Getting object out of an array within an array

I have a JSON array(dictionary?) of objects that are themselves an array. I need to find a value within one of these arrays so that I can compare it later. Part of my JSON data:
[
{
"Name": "Exhibitor",
"Url": "api/congress/exhibitor",
"ResourceType": "Data",
"LastMod": 1389106977
},
{
"Name": "Workshop",
"Url": "api/congress/workshop",
"ResourceType": "Data",
"LastMod": 1389106977
},
{
"Name": "Speaker",
"Url": "api/congress/Speaker",
"ResourceType": "Data",
"LastMod": 1389106977
},
]
My method receives a table name as a parameter and returns a time stamp. How would I receive the time stamp (1389106977) for the table "workshop" for example? This seems so simple but I cannot work it out for 'nested' arrays/dictionaries.
Thanks,
edit:
This is the my code with trojanfoe's added to it.
NSError* localError;
NSMutableArray *syncDataArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (syncDataArray)
{
NSNumber *lastMod = nil;
for (NSDictionary *dict in syncDataArray)
{
NSLog(#"current table is: %#", dict[#"Name"]);
if ([tableName isEqualToString:dict[#"Name"]])
{
lastMod = dict[#"LastMod"];
//break;
}
}
NSLog(#"LastMod = %#", lastMod);
}
else
{
NSLog(#"syncDataArray is empty");
}
This works perfectly and makes sense
The JSON data looks like an array of dictionaries, so you can iterate over the array and test for the "Name" entry:
NSArray *jsonData = ...; // You have converted JSON to Objective-C objects already
NSNumber *lastMod = nul;
for (NSDictionary *dict in jsonData) {
if ([#"Workshop" isEqualToString:dict[#"Name"]]) {
lastMod = dict[#"LastMod"];
break;
}
}
if (lastMod) {
// You found it
}
(Note I am not certain the type of object used to store the "LastMod" object, so you might need to do some debugging to find out).
EDIT If you make extensive use of this data you should immediately convert the JSON data into an array of (custom) model objects, which will make it easier to manipulate the data as your app becomes more complex.
You have an array for dictionaries so it would look something like :
NSNumber *timestamp = [[JSON objectAtIndex:index] objectForKey:#"LastMod"];
NSNumber *timestamp = response[1][#"LastMod"];

Deleting a particular object in NSDictionary

My Categories Dictionary is like this
"category": {
"position": 1,
"updated_at": "2012-11-21T11:02:14+05:30",
"is_default": false,
"name": "Ge",
"folders": [
{
How can i delete a particular Category object alone which has is_default as true?
I tried the following --
for(id obj in category )
{
if([obj isEqualToString:#"is_default"] && [[category objectForKey:#"is_default"] isEqualToNumber:#0])
{
but was unable to find a way to access the key of the particular category and hence delete it.
First thing first: You can not delete object from Dictionary(or Array Or Set) while Enumerating.
But it is not impossible.
Try this:
NSArray *keys = [category allKeys];
for(NSString *key in keys )
{
obj = [category objectForKey:key];
if([key isEqualToString:#"is_default"] && [[category objectForKey:#"is_default"] isEqualToNumber:#0])
{
[category removeObjectForKey:key]
}
}
Comment if you face any problem.
Al The Best.
You can get the keys (an object may be stored in the dictionary multiple times, using different keys) that your object is stored at like this:
NSArray *keys = [myDictionary allKeysForObject:obj];
Now that you have the key(s), it's easy to delete the object:
if (keys.count > 0) {
[myDictionary removeObjectForKey:keys.lastObject];
}
Searching through the values of a dictionary is a relatively slow operation, by the way. If you do this very often, a dictionary might not be the best data structure.

Resources