对iOS中的字符串进行encode

直接上代码:

/**
 对字符串进行encode,对于已经encode后的字符串不会处理

 @return encode后的字符串
 */
- (NSString *)encodingStr {
    if (self && [self isKindOfClass:[NSString class]] && self.length) {
        //判断是否需要encode,如果decode后跟当前一样,说明需要encode
        NSString *decodeString = [self stringByRemovingPercentEncoding];
        if ([decodeString isEqualToString:self]) {
            return [self stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        } else {
            return self;
        }
    } else {
        return @"";
    }
}

完事

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s