美文网首页
iOS NSData与其他类型互转

iOS NSData与其他类型互转

作者: iOS_肖晨 | 来源:发表于2017-09-30 17:34 被阅读770次

NSString -> NSData

NSString *aString = @"1234abcd";
NSData *aData = [aString dataUsingEncoding: NSUTF8StringEncoding];

NSData -> NSString

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

char -> NSData

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

NSData -> char

NSData *data;
char *test = [data bytes];

UIImage -> NSData

NSString *path = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"image.png"];
NSData *data = [NSData dataWithContentsOfFile:path];

NSData -> UIImage

UIImage *image = [UIImage imageWithData:data];

NSDictionary -> NSData

// 方法1:NSKeyedArchiver
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dict];

// 方法2:NSJSONSerialization
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:error];

NSData -> NSDictionary

// 方法1:NSKeyedUnarchiver
NSDictionary *dict = (NSDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:data];

// 方法2:NSJSONSerialization
NSDictionary *dict = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:error];

NSArray 同 NSDictionary,略。

注:

将继承自NSObject的自定义类转换为NSData,必须遵循NSCoding协议:

- (instancetype)initWithCoder:(NSCoder *)aDecoder;
- (void)encodeWithCoder:(NSCoder *)aCoder;

如下:

@interface Dog : NSObject
@property NSString *name;
@property NSInteger age;
@end
@implementation Book
#pragma mark - NSCoding
- (id)initWithCoder:(NSCoder *)decoder {
    self = [super init];
    self.name = [decoder decodeObjectForKey:@"name"];
    self.age = [decoder decodeIntegerForKey:@"age"];
    return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:self.name forKey:@"name"];
    [encoder encodeObject:self.age forKey:@"age"];
}
@end

相关文章

网友评论

      本文标题:iOS NSData与其他类型互转

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