Câu trả lời:
NSDadata -> NSData:
NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];
NSData -> NSDadata:
NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];
NSDadata -> 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 -> NSDadata
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];
Bạn có thể làm điều đó với bất kỳ lớp nào phù hợp với NSCoding.
Sử dụng NSJSONSerialization:
NSDictionary *dict;
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted
error:&error];
NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:dataFromDict
options:NSJSONReadingAllowFragments
error:&error];
Trả về mới nhất id, do đó, nên kiểm tra loại đối tượng được trả về sau khi bạn truyền (ở đây tôi chuyển sang NSDipedia).
Trong Swift 2, bạn có thể làm theo cách này:
var dictionary: NSDictionary = ...
/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedDataWithRootObject(dictionary)
/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as! NSDictionary
Trong Swift 3 :
/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedData(withRootObject: dictionary)
/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObject(with: data)
Any?loại. Nhưng nó cho thấy lỗi chuyển đổi từ NSDictionarysang NSData. Vì vậy, tôi đã thử mã của bạn. Nó không hoạt động.
NSDadata từ NSData
http://www.cocoanetic.com/2009/09/nsdipedia-from-nsdata/
NSDixi đến NSData
Bạn có thể sử dụng lớp NSPropertyListSerialization cho điều đó. Hãy xem phương pháp của nó:
+ (NSData *)dataFromPropertyList:(id)plist format:(NSPropertyListFormat)format
errorDescription:(NSString **)errorString
Trả về một đối tượng NSData chứa danh sách thuộc tính đã cho theo định dạng đã chỉ định.
Hãy thử cái này
NSError *error;
NSDictionary *responseJson = [NSJSONSerialization JSONObjectWithData:webData
options:NSJSONReadingMutableContainers
error:&error];
response, không phải responce. Tôi đã sửa lỗi này cho bạn.