首页 > 代码库 > NSData NSDate NSString NSArray NSDictionary 相互转换
NSData NSDate NSString NSArray NSDictionary 相互转换
// NSData NSDate NSString NSArray NSDictionary json NSString *string = @"hello word"; NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; NSArray *array = [NSArray arrayWithObjects:@"1",@"2",@"3",nil]; NSString *dateString = @"19891123"; NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys: @"hello", @"word", @"chen", @"lu", @"jin", @"mei", @"cerastes", @"hehe",nil]; // NSString to NSData NSData *string2data = [string dataUsingEncoding:NSUTF8StringEncoding]; NSLog(@"%@",string2data); // NSData to NSString NSString *data2String = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"dataString = %@",data2String); // NSArray to NSData NSData *arry2data = [NSKeyedArchiver archivedDataWithRootObject:array]; // NSData to NSArray NSArray *data2arry = [NSKeyedUnarchiver unarchiveObjectWithData:arry2data]; NSLog(@"%@ /n %@",arry2data,data2arry); // NSString to NSDate NSDate *string2date = [self convertDateFromString:dateString withFormattre:@"yyyyMMdd"]; NSLog(@"date = %@",string2date); // NSDate to NSString NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSString *date2string = [dateFormatter stringFromDate:[NSDate date]]; NSLog(@"%@", date2string); // NSArray to NSString NSString *arry2String = [array componentsJoinedByString:@" "]; NSLog(@"string = %@",arry2String); // NSString to NSArray NSArray *string2Arry = [arry2String componentsSeparatedByString:@" "]; NSLog(@" %@",string2Arry); // NSDictionary to NSData: NSMutableData *dic2data = [[NSMutableData alloc] init]; NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:dic2data]; [archiver encodeObject:dic forKey:@"Some Key Value"]; [archiver finishEncoding]; NSLog(@"%@",dic2data); // NSData to NSDictionary NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:dic2data]; NSDictionary *data2dic = [unarchiver decodeObjectForKey:@"Some Key Value"]; [unarchiver finishDecoding]; NSLog(@"%@",data2dic); // NSDictionary to NSString NSString *dic2string=[dic JSONRepresentation]; //这个方法是SBJson类库里的,需要导入SBJson.h NSLog(@"%@",dic2string); // NSString to NSDictionary NSError *error = nil; NSDictionary *string2dic = [NSJSONSerialization JSONObjectWithData: [dic2string dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &error]; NSLog(@"%@",string2dic);
NSData NSDate NSString NSArray NSDictionary 相互转换
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。