2012-02-20 121 views
2

任何人都可以提供有关在Objective-C(用于iPhone开发)中的内存中压缩和解压缩字符串的教程/文档。在内存中压缩/解压缩字符串

我在看Objective-Zip,但它似乎只能将压缩数据写入文件。

+0

如果想使用zlib,请参阅[此帖](http://stackoverflow.com/questions/8425012/is-there-a-practical-way-to- compress-nsdata/11389847#11389847)。如果想要使用bzlib,请参见[本文](http://stackoverflow.com/questions/9577735/how-compress-data-in-memory-buffer-by-using-libbz2-library-in-c-program/ 11390277#11390277)也是如此。 – 2012-07-09 06:57:52

回答

1

给你举个例子

@interface NSString (Gzip) 
- (NSData *)compress; 
@end 



@implementation NSString (Gzip) 

- (NSData *)compress 
{ 
    size_t len = [self length]; 
    size_t bufLen = (len + 12) * 1.001; 
    u_char *buf = (u_char *)malloc(bufLen); 
    if (buf == NULL) { 
     NSLog(@"malloc error"); 
     return nil; 
    } 
    int err = compress(buf, &bufLen, (u_char *)[[self dataUsingEncoding:NSUTF8StringEncoding] bytes], len); 
    if (err != Z_OK) { 
     NSLog(@"compress error"); 
     free(buf); 
     return nil; 
    } 

    NSData *rtn = [[[NSData alloc] initWithBytes:buf length:bufLen] autorelease]; 
    free(buf); 

    return rtn; 
} 


@end