数据类型转换

来源:互联网 发布:学做淘宝到哪里去学 编辑:程序博客网 时间:2024/06/08 15:40

import “RootViewController.h”

@interface RootViewController ()

@end

@implementation RootViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //********************NSString 相关***********************//
    //NSDictionary 转NSString
    //用字符串将nsarray的元素拼接起来
    NSArray *array = [NSArray arrayWithObjects:@”hello”,@”world”, nil];
    NSString *string = [array componentsJoinedByString:@” “];
    NSLog(@”string = %@”,string );

    //nsdata 转 nsstring
    NSString *strurl = @”www.”;
    NSURL *url = [NSURL URLWithString:strurl];
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSString *datastr1 = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

    // NSString 转换成NSData 对象

    NSData* Data = [@”testdata” dataUsingEncoding:NSUTF8StringEncoding];

    // NSData 转换成char*

    NSData *data2;
    const char* a=[data2 bytes];

    //nsstring zhuan char
    NSString *str = @”dad”;
    const char *q =[str UTF8String];

    // char* 转换成NSData对象

    Byte* tempData = malloc(sizeof(Byte)*16);
    NSData *content=[NSData dataWithBytes:tempData length:16];

// NSNumber转NSString:

// 假设现有一NSNumber的变量A,要转换成NSString类型的B

// 方法如下:

NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];NSNumber *A = [[NSNumber alloc]initWithInt:5];NSString *B;B = [numberFormatter stringFromNumber:A];[numberFormatter release];

// nsstring和float 还有int之间的转换

NSString *tempA = @"123";NSString *tempB = @"456";

// 1,字符串拼接

NSString *newString = [NSString stringWithFormat:@"%@%@",tempA,tempB];

// 2,字符转int

int intString = [newString intValue];

// 3,int转字符

NSString *stringInt = [NSString stringWithFormat:@"%d",intString];

//4,字符转float

float floatString = [newString floatValue];

// 5,万能公式其他转字符

NSString *stringFloat = [NSString stringWithFormat:@"%f",floatString];

//

}
//nsdictionary 相关
//字典nsdictionary 转成json
- (NSString )dictionaryToJason:(NSDictionary )dic
{
NSData *jsondata = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
return [[NSString alloc]initWithData:jsondata encoding:NSUTF8StringEncoding];

}

  • (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    }

/*

pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/

@end

1 0
原创粉丝点击