美文网首页
iOS NSData的相互转换

iOS NSData的相互转换

作者: Lambo316 | 来源:发表于2016-06-28 09:58 被阅读2270次

    1、 NSData && NSString

    NSData *data = [NSData dataWithContentsOfURL:url];

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

    NSData *subData = [str dataUsingEncoding:NSUTF8StringEncoding];

    2、NSData && UIImage

    UIImage *image = [UIImage imageNamed:@"11.png"];

    NSData *imageData = UIImageJPEGRepresentation(image, 1);

    UIImage *subImage = [UIImage imageWithData:imageData];

    3、NSData && NSArray

    //利用归档和反归档进行转换

    NSArray *array = @[@"1",@"2",@"3"];

    NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:array];

    NSArray *subArray = [NSKeyedUnarchiver unarchiveObjectWithData:arrayData];

    4、NSData && NSDictionary

    //利用归档和反归档进行转换

    NSDictionary *dict = @{@"name":@"zhang",@"age":@"16",@"gender":@"F"};

    NSData *dictData = [NSKeyedArchiver archivedDataWithRootObject:dict];

    NSDictionary *subDict = [NSKeyedUnarchiver unarchiveObjectWithData:dictData];

    5、NSData && NSString && UIImage

    //用于存储数据库中的数据

    UIImage *image = [UIImage imageNamed:@"11.png"];

    NSData *imageData = UIImageJPEGRepresentation(image, 1);

    NSString *imageStr = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

    NSData *subImageData = [[NSData alloc] initWithBase64EncodedString:imageStr options:NSDataBase64DecodingIgnoreUnknownCharacters];

    UIImage *subImage = [UIImage imageWithData:subImageData];

    相关文章

      网友评论

          本文标题:iOS NSData的相互转换

          本文链接:https://www.haomeiwen.com/subject/dcktjttx.html