2012-02-20 176 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