NSString+Safety.h 2.57 KB
//
//  NSString+BBASubstring.h
//  BBAFoundation
//
//  Created by Zhu,Yusong on 2018/9/19.
//  Copyright © 2018年 Baidu. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "BDPFoundationDefines.h"

/*
 * 字符串的安全相关的扩展
 * 详细介绍请看README-SafeAPI
 */

NS_ASSUME_NONNULL_BEGIN

@interface NSString (Safety)

/**
 * @brief substringFromIndex 的安全方法
 *
 * @param from 截取的开始位置
 * @return NSString from 若越界,返回 @""
 */
- (nullable NSString *)safe_substringFromIndex:(NSUInteger)from BDP_FOUNDATION_DEPRECATED("please use bdp_safeSubstringFromIndex:");
- (nullable NSString *)bdp_safeSubstringFromIndex:(NSUInteger)from;

/**
 * @brief substringToIndex 的安全方法
 *
 * @param to 截取的终止位置
 * @return NSString to 若越界,返回 self
 */
- (nullable NSString *)safe_substringToIndex:(NSUInteger)to BDP_FOUNDATION_DEPRECATED("please use bdp_safeSubstringToIndex:");
- (nullable NSString *)bdp_safeSubstringToIndex:(NSUInteger)to;

/**
 * @brief substringWithRange 的安全方法
 *
 * @param range 截取的范围
 * @return NSString range.location 若越界返回 @"" range.location + range.length 取不超过 self.length
 */
- (nullable NSString *)safe_substringWithRange:(NSRange)range BDP_FOUNDATION_DEPRECATED("please use bdp_safeSubstringWithRange:");
- (nullable NSString *)bdp_safeSubstringWithRange:(NSRange)range;

/**
 * @brief 截取指定 index 的字符串, 相当于 safe_substringWithRange:NSMakeRange(index, 1)
 *
 * @param index 截取的位置
 * @return NSString
 */
- (nullable NSString *)safe_substringAtIndex:(NSUInteger)index BDP_FOUNDATION_DEPRECATED("please use bdp_safeSubstringAtIndex:");
- (nullable NSString *)bdp_safeSubstringAtIndex:(NSUInteger)index;

/**
 * @brief 对于一些超级长的中午字符,超过 500个在iPhone5上面,使用 stringByAddingPercentEncodingWithAllowedCharacters 会占用过多内存导致 `EXC_BAD_ACCESS` crash,采取分段处理,减少内存占用。
 *
 * @param allowedCharacters Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored.
 * @return Returns a new string made from the receiver by replacing all characters not in the allowedCharacters set with percent encoded characters.
 */
- (NSString *)safe_stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters BDP_FOUNDATION_DEPRECATED("please use bdp_safeStringByAddingPercentEncodingWithAllowedCharacters:");
- (NSString *)bdp_safeStringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters;

@end

NS_ASSUME_NONNULL_END