一: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转换
- //NSDictionary -> JSON: //这个方法是SBJson类库里的,需要导入SBJson.h
- NSString *jsonStr=[dict JSONRepresentation];
- //建议(特别是http取回来的jsonStr转换如下)
- //JSON->NSDictionary:
- NSData *jsonData = [testJsonStr dataUsingEncoding:NSUTF8StringEncoding];
- NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil]
//摘录其他同学的
NSData 与 Byte
NSData-> Byte数组
NSString *testString = @"1234567890";
NSData *testData = [testString dataUsingEncoding: NSUTF8StringEncoding];
Byte *testByte = (Byte *)[testData bytes];
for(int i=0;i<[testData length];i++)
printf("testByte = %d\n",testByte[i]);
Byte数组-> NSData
Byte byte[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23};
NSData *adata = [[NSData alloc] initWithBytes:byte length:24];
Byte数组->16进制数
Byte *bytes = (Byte *)[aData bytes];
NSString *hexStr=@"";
for(int i=0;i<[encryData length];i++)
{
NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff]; ///16进制数
if([newHexStr length]==1)
hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
else
hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
}
NSLog(@"bytes 的16进制数为:%@",hexStr);