博客> iOS各种数据类型之间的转换关系
iOS各种数据类型之间的转换关系
2017-12-12 21:47 评论:0 阅读:478 蓝色了记忆
ios 转换 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 = @"19910927";
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                     @"hello", @"word",
                     @"husband", @"zhangbin",
                     @"wife", @"lijiaojiao",
                     @"time", @"1314",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);

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

NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];

B = [numberFormatter stringFromNumber:A];

收藏
0
sina weixin mail 回到顶部