2

Can anyone provide me a tutorial / documentation on compressing and decompressing strings in memory in objective-c (for iPhone development).

I am looking at Objective-Zip, but it only seems to work by writing the compressed data to a file.

Jonathan Smith
  • 2,390
  • 1
  • 34
  • 60
  • If wanting to use zlib, see [this post](http://stackoverflow.com/questions/8425012/is-there-a-practical-way-to-compress-nsdata/11389847#11389847) on SO. If wanting to use bzlib, see [this post](http://stackoverflow.com/questions/9577735/how-compress-data-in-memory-buffer-by-using-libbz2-library-in-c-program/11390277#11390277) on SO too. – lucasart Jul 09 '12 at 06:57

1 Answers1

1

give you an example

@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
xda1001
  • 2,449
  • 16
  • 18