iOS经常需要用到数据类型的转换,下面列举一下常用类型的转换。
1.NSDictionary类型转换为NSData类型:
- //NSDictionary -> NSData:
- NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
- @"balance", @"key",
- @"remaining balance", @"label",
- @"45", @"value",
- @"USD", @"currencyCode",nil];
- NSMutableData *data = [[NSMutableData alloc] init];
- NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
- [archiver encodeObject:params forKey:@"Some Key Value"];
- [archiver finishEncoding];
2.NSData类型转换为NSDictionary类型:
- //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];
3.NSDictionary类型转换为JSON数据类型:
- //NSDictionary -> JSON:
- NSString *jsonStr=[dict JSONRepresentation];
注意JSON与NSDictionary类型的转换一般会用到第三方公开的JSON库,读者可以在网上找到很多。