Risposte:
NSDictionary -> NSData:
NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];
NSData -> NSDictionary:
NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];
NSDictionary -> NSData:
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:yourDictionary forKey:@"Some Key Value"];
[archiver finishEncoding];
[archiver release];
// Here, data holds the serialized version of your dictionary
// do what you need to do with it before you:
[data release];
NSData -> NSDictionary
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSDictionary *myDictionary = [[unarchiver decodeObjectForKey:@"Some Key Value"] retain];
[unarchiver finishDecoding];
[unarchiver release];
[data release];
Puoi farlo con qualsiasi classe conforme a NSCoding.
Usa NSJSONSerialization:
NSDictionary *dict;
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted
error:&error];
NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:dataFromDict
options:NSJSONReadingAllowFragments
error:&error];
Gli ultimi ritorni id
, quindi è una buona idea controllare il tipo di oggetto restituito dopo il cast (qui ho eseguito il cast su NSDictionary).
In Swift 2 puoi farlo in questo modo:
var dictionary: NSDictionary = ...
/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedDataWithRootObject(dictionary)
/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as! NSDictionary
In Swift 3 :
/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedData(withRootObject: dictionary)
/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObject(with: data)
Any?
tipo. Ma ha mostrato un errore durante la conversione da NSDictionary
a NSData
. Quindi ho provato il tuo codice. Non ha funzionato.
NSDictionary da NSData
http://www.cocoanetics.com/2009/09/nsdictionary-from-nsdata/
NSDictionary in NSData
È possibile utilizzare la classe NSPropertyListSerialization per questo. Dai un'occhiata al suo metodo:
+ (NSData *)dataFromPropertyList:(id)plist format:(NSPropertyListFormat)format
errorDescription:(NSString **)errorString
Restituisce un oggetto NSData contenente un determinato elenco di proprietà in un formato specificato.
Provi questo, per favore
NSError *error;
NSDictionary *responseJson = [NSJSONSerialization JSONObjectWithData:webData
options:NSJSONReadingMutableContainers
error:&error];
response
è responce
. Ho corretto questo per te.