您的位置:首页 > 其它

NSData,NSImage,NSDictionary,NSString,NSInteger,Float,NSURL互相转换汇总

2014-11-04 17:36 435 查看
NSString 转换成NSData 对象

NSData* xmlData = [@"testdata" dataUsingEncoding:NSUTF8StringEncoding];


NSData 转换成NSString对象

NSData * data;
NSString *result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];


NSData 转换成char*

NSData *data; 
char *test=[data bytes];


char* 转换成NSData对象
byte* tempData = malloc(sizeof(byte)*16); 
NSData *content=[NSData dataWithBytes:tempData length:16];


NSString和NSURL 转换

//NSString->NSURL
NSString *urlString=[@"http://www.google.com" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:urlString];
//NSURL->NSString
NSString *urlString=[[url absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];


NSString和NSData转换(即可作json串互相转换)

//NSData-> NSString
NSString *testString = [[NSString alloc] initWithData:testData encoding:NSUTF8StringEncoding];
//NSString->NSData
NSString *aString = @"我是NSString";
NSData *testData = [testString dataUsingEncoding: NSUTF8StringEncoding];


NSData和NSImage转换

//NSData->UIImage
UIImage *testImage = [UIImage imageWithData: imageData];
//UIImage->NSData
NSData *imageData = UIImagePNGRepresentation(testImage)
//或者
NSData *imageData = UIImageJPEGRepresentation(testImage,1.0)


NSData和NSDictionary转换

//NSData-->NSDictionary
NSDictionary *testDict = [NSJSONSerialization JSONObjectWithData:testData options:NSJSONReadingMutableContainers error:nil]
//或者
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:testData];
NSDictionary *myDictionary = [[unarchiver decodeObjectForKey:@"Some Key Value"] retain];
[unarchiver finishDecoding];
//NSDictionay --> NSData
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:params forKey:@"Some Key Value"];
[archiver finishEncoding];


NSDictionary和JSON转换

JSON:  //这个方法是SBJson类库里的,需要导入SBJson.h
NSString *jsonStr=[dict JSONRepresentation];
//或者原生类库中
NSData      *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString    *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//建议(特别是http取回来的jsonStr转换如下)
//JSON->NSDictionary:
NSData *jsonData = [testJsonStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: