Reputation: 2599
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.
Upvotes: 2
Views: 2264
Reputation: 2459
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
Upvotes: 1