数据类型与char*类型的相互转换(NSData <-> char *)
NSData * data;
char * chars = (char *)[data bytes];
Byte * tempData = malloc(sizeof(Byte)*16);
NSData * data = [NSData dataWithBytes:tempData length:16];
字符串类型与数据类型的相互转换(NSString <-> NSData )
+ (NSData *)dataWithString:(NSString *)string{
NSData * data = [string dataUsingEncoding:NSUTF8StringEncoding];
return data;
}
+ (NSString *)stringWithData:(NSData *)data{
NSString * string = [[NSString alloc] initWithData:dataencoding:NSUTF8StringEncoding];
return string;
}
字典类型与JSON类型的相互转换(NSDictionary <-> JSON )
+ (NSDictionary *)dictionaryWithJSON:(NSString *)JSON{
if (!JSON) return nil;
NSData * data = [JSON dataUsingEncoding:NSUTF8StringEncoding];
NSError * error = nil;
NSDictionary * dictionary = [NSJSONSerialization JSONObjectWithData:dataoptions:NSJSONReadingMutableContainers error:&error];
if (error) {
NSLog(@"JSON解析失败:%@",error);
return nil;
}
return dictionary;
}
+ (NSString *)JSONWithDictionary:(NSDictionary *)dictionary{
NSError * error = nil;
NSData * data = [NSJSONSerialization dataWithJSONObject:dictionaryoptions:NSJSONWritingPrettyPrinted error:&error];
NSString * JSON = [[NSString alloc] initWithData:dataencoding:NSUTF8StringEncoding];
return JSON;
}