内存

NSData -bytes方法遇到的坑

2017-11-30  本文已影响25人  SnoopPanda

在做NSData转化成C字符串的时候, 偶然发现了-bytes这个方法非常的简洁, 于是就放在新需求的开发之中, 一切看上去很美. 结果并不理想, 因为每次通过-bytes这个方法得到的结果总是不一样, 字符串后面会有乱七八糟的东西. 于是做了一个小Demo测试了一下.

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    NSDictionary *dict = @{ @"name" : @"xiaoming",
                            @"age": @"18",
                            @"sex": @"Man"
                            };
    NSData *data1 = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
    char *str1 = (char *)[data1 bytes];
    
    NSData *data2 = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:nil];
    NSString *tempStr = [[NSString alloc] initWithData:data2 encoding:NSUTF8StringEncoding];
    char *str2 = [tempStr UTF8String];
    
    NSLog(@"\n1 = %s\n2 = %s", str1, str2);
}

以上是两种方式来做NSData转换, 运行起来的结果如下图:


运行结果.png

点进去看了一下该方法的介绍.

     The -bytes method returns a pointer to a contiguous region of memory managed by the receiver.
 If the regions of memory represented by the receiver are already contiguous, it does so in O(1) time, otherwise it may take longer

翻译过来就是说-bytes这个方法的接受者指向一段连续的内存, 因为是连续的内存就可能包含除NSData以外的内存空间所存放的值, 这就是结果总是不一样的原因. 怎么验证呢?

上一篇下一篇

猜你喜欢

热点阅读