views:

114

answers:

2

I just started Objective-C recently, and this has once again gotten me to the point of asking SO for help. I need to rewrite this method so that I can call it using [self URLEncodedString];

This is what the method currently looks like -

- (NSString *)URLEncodedString {
      NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8);
      [result autorelease];
      return result;
}

But I can't call it like [self URLEncodedString]; How can I rewrite it so that it would work for me to be able to call it using [self URLEncodedString];?

P.S. Calling it via [strValue URLEncodedString]; doesn't work, hence the reason I'm making this post.

Thanks for any help!

+7  A: 

I think what you're asking for is to create an NSString category which will encode your string.

You need to create a new set of files, name them something that makes sense (NSString+URLEncoding).

In the .h file, you'll need something like this:

@interface NSString (URLEncoding)
- (NSString*)URLEncodedString;
@end

Then in your .m file:

@implementation NSString (URLEncoding)

- (NSString *)URLEncodedString {
      NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8);
      [result autorelease];
      return result;
}

@end

When you want to use this method, you'll need to make sure you import "NSString+URLEncoding.h".

You can then do something like this:

NSString * firstString = @"Some string to be encoded %&^(&(!@£$%^&*";
NSString * encodedString = [firstString URLEncodedString];

Hope that helps.

Tom Irving
+2  A: 

Why not just use the NSString instance method stringByAddingPercentEscapesUsingEncoding?

Kendall Helmstetter Gelner