/* NSString.h
Copyright (c) 1994-2014, Apple Inc. All rights reserved.
*/
//短正值整型,不少于16位
typedef unsigned short unichar;
#import <limits.h>
//根类,提供基本运行能力的接口
#import <Foundation/NSObject.h>
//截取字符串或者数组
#import <Foundation/NSRange.h>
//C标准函数库的头文件,stdarg主要目的是位让函数能够接收不定参数
#import<stdarg.h>
//@class 告诉编译器,其后面声明的名称是类的名称
@class NSData, NSArray, NSDictionary, NSCharacterSet, NSURL, NSError, NSLocale;
//异常处理处理串定义
FOUNDATION_EXPORT NSString * const NSParseErrorException; // raised by -propertyList
//字符串最大值定义
#define NSMaximumStringLength (INT_MAX-1)
/* These options apply to the various search/find and comparison methods (except where noted).
*/
//下面部分主要用于搜索,查找,比较
typedef NS_OPTIONS(NSUInteger, NSStringCompareOptions) {
NSCaseInsensitiveSearch = 1,//不区分大小写比较
NSLiteralSearch = 2, //区分大小写比较
NSBackwardsSearch = 4, //从字符串末尾开始搜索
NSAnchoredSearch = 8,//搜索限制范围的字符串
NSNumericSearch = 64, //按照字符串里的数字为依据,算出顺序
NSDiacriticInsensitiveSearch NS_ENUM_AVAILABLE(10_5, 2_0) = 128, //忽略“-”的比较
NSWidthInsensitiveSearch NS_ENUM_AVAILABLE(10_5, 2_0) = 256, //忽略字符串的长度,比较出结果
NSForcedOrderingSearch NS_ENUM_AVAILABLE(10_5, 2_0) = 512,//忽略不区分大小写比较的选项
NSRegularExpressionSearch NS_ENUM_AVAILABLE(10_7, 3_2) = 1024//定期搜索
};
/* Note that in addition to the values explicitly listed below, NSStringEncoding supports encodings provided by CFString.
See CFStringEncodingExt.h for a list of these encodings.
See CFString.h for functions which convert between NSStringEncoding and CFStringEncoding.
*/
//一些编码的转换
enum {
NSASCIIStringEncoding = 1, /* 0..127 only */
NSNEXTSTEPStringEncoding = 2,
NSJapaneseEUCStringEncoding = 3,
NSUTF8StringEncoding = 4,
NSISOLatin1StringEncoding = 5,
NSSymbolStringEncoding = 6,
NSNonLossyASCIIStringEncoding = 7,
NSShiftJISStringEncoding = 8, /* kCFStringEncodingDOSJapanese */
NSISOLatin2StringEncoding = 9,
NSUnicodeStringEncoding = 10,
NSWindowsCP1251StringEncoding = 11, /* Cyrillic; same as AdobeStandardCyrillic */
NSWindowsCP1252StringEncoding = 12, /* WinLatin1 */
NSWindowsCP1253StringEncoding = 13, /* Greek */
NSWindowsCP1254StringEncoding = 14, /* Turkish */
NSWindowsCP1250StringEncoding = 15, /* WinLatin2 */
NSISO2022JPStringEncoding = 21, /* ISO 2022 Japanese encoding for e-mail */
NSMacOSRomanStringEncoding = 30,
NSUTF16StringEncoding = NSUnicodeStringEncoding, /* An alias for NSUnicodeStringEncoding */
NSUTF16BigEndianStringEncoding = 0x90000100, /* NSUTF16StringEncoding encoding with explicit endianness specified */
NSUTF16LittleEndianStringEncoding = 0x94000100, /* NSUTF16StringEncoding encoding with explicit endianness specified */
NSUTF32StringEncoding = 0x8c000100,
NSUTF32BigEndianStringEncoding = 0x98000100, /* NSUTF32StringEncoding encoding with explicit endianness specified */
NSUTF32LittleEndianStringEncoding = 0x9c000100 /* NSUTF32StringEncoding encoding with explicit endianness specified */
};
//字符串编码
typedef NSUInteger NSStringEncoding;
//编码和解码的转换
typedef NS_OPTIONS(NSUInteger, NSStringEncodingConversionOptions) {
NSStringEncodingConversionAllowLossy = 1,
NSStringEncodingConversionExternalRepresentation = 2
};
//字符串转化异常
FOUNDATION_EXPORT NSString * const NSCharacterConversionException;
@interface NSString : NSObject <NSCopying, NSMutableCopying, NSSecureCoding>
/* NSString primitive (funnel) methods. A minimal subclass of NSString just needs to implement these, although we also recommend getCharacters:range:. See below for the other methods.
*/
@property (readonly) NSUInteger length;
- (unichar)characterAtIndex:(NSUInteger)index;
- (instancetype)init NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;
@end
@interface NSString (NSStringExtensionMethods)
//unichar是两字节长的char,代表unicode的一个字符,截取字符串指定段
- (void)getCharacters:(unichar *)buffer range:(NSRange)aRange;
//截取指定位置后面的字符串
- (NSString *)substringFromIndex:(NSUInteger)from;
//截取指定长度的字符串,从索引0开始
- (NSString *)substringToIndex:(NSUInteger)to;
//截取字符串指定段
- (NSString *)substringWithRange:(NSRange)range; // Hint: Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up composed characters
/* In the compare: methods, the range argument specifies the subrange, rather than the whole, of the receiver to use in the comparison. The range is not applied to the search string. For example, [@"AB" compare:@"ABC" options:0 range:NSMakeRange(0,1)] compares "A" to "ABC", not "A" to "A", and will return NSOrderedAscending.
*/
//比较字符串
- (NSComparisonResult)compare:(NSString *)string;
//以NSStringCompareOptions的条件比较字符串
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask;
//以某些条件比较字符串至指定段
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)compareRange;
//以某些限制+本地化(语言环境)比较条件比较字符串至指定段
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)compareRange locale:(id)locale; // locale arg used to be a dictionary pre-Leopard. We now accept NSLocale. Assumes the current locale if non-nil and non-NSLocale. nil continues to mean canonical compare, which doesn't depend on user's locale choice.
//不区分大小写比较
- (NSComparisonResult)caseInsensitiveCompare:(NSString *)string;
//本地化比较
- (NSComparisonResult)localizedCompare:(NSString *)string;
//不区分大小写本地化比较
- (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)string;
/* localizedStandardCompare:, added in 10.6, should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate. The exact behavior of this method may be tweaked in future releases, and will be different under different localizations, so clients should not depend on the exact sorting order of the strings.
*/
//
NSNumericSearch:它对字符串里的数字排序,所以 “Section 9” < “Section 20” < “Section 100.”
NSDiacriticInsensitiveSearch:“A” 等同于 “Å” 等同于 “Ä.”
NSWidthInsensitiveSearch:一些东亚文字(平假名和片假名)有全宽与半宽两种形式。
很值得一提的是-localizedStandardCompare:,它排序的方式和 Finder 一样。它对应的选项是NSCaseInsensitiveSearch、NSNumericSearch、NSWidthInsensitiveSearch 以及 NSForcedOrderingSearch。如果我们要在 UI 上显示一个文件列表,用它就最合适不过了。
- (NSComparisonResult)localizedStandardCompare:(NSString *)string NS_AVAILABLE(10_6, 4_0);
//测试两个字符串是否相等
- (BOOL)isEqualToString:(NSString *)aString;
//测试字符串是否以nsstring(某个字符串)开始
- (BOOL)hasPrefix:(NSString *)aString;
//测试字符串是否以nsstring(某个字符串)结尾
- (BOOL)hasSuffix:(NSString *)aString;
/* containsString: returns YES if the target string is contained within the receiver. Same as calling rangeOfString:options: with no options, thus doing a case-sensitive, non-literal search. localizedCaseInsensitiveContainsString: is the case-insensitive variant. Note that it takes the current locale into effect as well. Locale-independent case-insensitive operation, and other needs can be achieved by calling rangeOfString:options:range:locale: directly.
*/
//检测某个字符串是否包含aString(另一个)字符串 区分大小写
- (BOOL)containsString:(NSString *)aString NS_AVAILABLE(10_10, 8_0);
//本地化检测某个字符串是否包含另一个字符串 不区分大小写和音调
- (BOOL)localizedCaseInsensitiveContainsString:(NSString *)aString NS_AVAILABLE(10_10, 8_0);
/* These methods return length==0 if the target string is not found. So, to check for containment: ([str rangeOfString:@"target"].length > 0). Note that the length of the range returned by these methods might be different than the length of the target string, due composed characters and such.
*/
//检测一个字符串在另一个字符串的开始位置和长度 返回一个NSRange
- (NSRange)rangeOfString:(NSString *)aString;
//以某些条件检测一个字符串在另一个字符串的开始位置和长度 返回一个NSRange
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask;
//以某些限制条件搜索字符串One在于字符串Two指定位置段
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)searchRange;
//以某些限制条件+本地化限制搜索字符串One在于字符串Two指定位置段
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)searchRange locale:(NSLocale *)locale NS_AVAILABLE(10_5, 2_0);
/* These return the range of the first character from the set in the string, not the range of a sequence of characters.
*/
//指定字符集搜索
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet;
//以某些条件指定字符集搜索
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet options:(NSStringCompareOptions)mask;
//以某些条件指定字符集搜索指定位置段
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet options:(NSStringCompareOptions)mask range:(NSRange)searchRange;
//以字符串的字符编码指定索引查找位置
- (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)index;
//以字符串的字符编码指定区域段查找位置
- (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range NS_AVAILABLE(10_5, 2_0);
//将字符串One添加到字符串Two后面
- (NSString *)stringByAppendingString:(NSString *)aString;
//将多个字符串添加到字符串Two后面
- (NSString *)stringByAppendingFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
/* The following convenience methods all skip initial space characters (whitespaceSet) and ignore trailing characters. NSScanner can be used for more "exact" parsing of numbers.
*/
//返回转化的double类型
@property (readonly) double doubleValue;
//返回转化的float类型
@property (readonly) float floatValue;
//返回转化的int类型
@property (readonly) int intValue;
//返回转化的NSInteger类型(32位系统NSInteger是一个int,当是64位时,是64位)
@property (readonly) NSInteger integerValue NS_AVAILABLE(10_5, 2_0);
//返回转化的长int类型
@property (readonly) long long longLongValue NS_AVAILABLE(10_5, 2_0);
//返回转化的BOOL类型
@property (readonly) BOOL boolValue NS_AVAILABLE(10_5, 2_0); // Skips initial space characters (whitespaceSet), or optional -/+ sign followed by zeroes. Returns YES on encountering one of "Y", "y", "T", "t", or a digit 1-9. It ignores any trailing characters.
//字符串转化为数组
- (NSArray *)componentsSeparatedByString:(NSString *)separator;
//依据字符编码,分割字符串
- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator NS_AVAILABLE(10_5, 2_0);
//one字符串是否在two字符串的开头
- (NSString *)commonPrefixWithString:(NSString *)aString options:(NSStringCompareOptions)mask;
/* The following three case methods perform the canonical (non-localized) mappings. They are suitable for programming operations that require stable results not depending on the user's locale preference. For localized case mapping for strings presented to users, use their corresponding methods with locale argument below.
*/
//所有的字符串转化为大写
@property (readonly, copy) NSString *uppercaseString;
//所有的字符串转化为小写
@property (readonly, copy) NSString *lowercaseString;
//所有的单词首字母转化为大写
@property (readonly, copy) NSString *capitalizedString;
/* The following methods perform localized case mappings based on the locale specified. Passing nil indicates the canonical mapping. For the user preference locale setting, specify +[NSLocale currentLocale].
*/
//所有字符串转化为大写(本地化)
- (NSString *)uppercaseStringWithLocale:(NSLocale *)locale NS_AVAILABLE(10_8, 6_0);
//所有字符转化为小写(本地化)
- (NSString *)lowercaseStringWithLocale:(NSLocale *)locale NS_AVAILABLE(10_8, 6_0);
//所有单词首字母转化为大写(本地化)
- (NSString *)capitalizedStringWithLocale:(NSLocale *)locale NS_AVAILABLE(10_8, 6_0);
//字符串替换
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set;
//将字符串two指定索引段添加索引段字符串one
- (NSString *)stringByPaddingToLength:(NSUInteger)newLength withString:(NSString *)padString startingAtIndex:(NSUInteger)padIndex;
//指定段分行去字符串
- (void)getLineStart:(NSUInteger *)startPtr end:(NSUInteger *)lineEndPtr contentsEnd:(NSUInteger *)contentsEndPtr forRange:(NSRange)range;
//返回字符串指定段的位置和长度
- (NSRange)lineRangeForRange:(NSRange)range;
//指定段分段取字符串
- (void)getParagraphStart:(NSUInteger *)startPtr end:(NSUInteger *)parEndPtr contentsEnd:(NSUInteger *)contentsEndPtr forRange:(NSRange)range;
//指定段分段的位置和长度
- (NSRange)paragraphRangeForRange:(NSRange)range;
//将字符串分解成数组,使用componentsSeparatedByString:这个方法,或者enumerateSubstringsInRange:options:usingBlock:。如果是按照行来进行分解可以使用option这个参数传NSStringEnumerationByLines
typedef NS_OPTIONS(NSUInteger, NSStringEnumerationOptions) {
// Pass in one of the "By" options:
NSStringEnumerationByLines = 0, // 按照行来分解
NSStringEnumerationByParagraphs = 1, // 按照段落来分解
NSStringEnumerationByComposedCharacterSequences = 2, // 按照字母来分解
NSStringEnumerationByWords = 3,// 按照单词来分解
NSStringEnumerationBySentences = 4,// 按照句子来分解
// ...and combine any of the desired additional options:
NSStringEnumerationReverse = 1UL << 8,// 按照反向遍历
NSStringEnumerationSubstringNotRequired = 1UL << 9,
NSStringEnumerationLocalized = 1UL << 10 // User's default locale
};
/* In the enumerate methods, the blocks will be invoked inside an autorelease pool, so any values assigned inside the block should be retained.
*/
//检查是否在指定范围内是否有匹配的字符串
- (void)enumerateSubstringsInRange:(NSRange)range options:(NSStringEnumerationOptions)opts usingBlock:(void (^)(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop))block NS_AVAILABLE(10_6, 4_0);
//枚举字符串所有行
- (void)enumerateLinesUsingBlock:(void (^)(NSString *line, BOOL *stop))block NS_AVAILABLE(10_6, 4_0);
//返回字符串
@property (readonly, copy) NSString *description;
//返回字符串哈希地址
@property (readonly) NSUInteger hash;
/*** Encoding methods ***/
//字符串最快编码值
@property (readonly) NSStringEncoding fastestEncoding; // Result in O(1) time; a rough estimate
//字符串最小编码值
@property (readonly) NSStringEncoding smallestEncoding; // Result in O(n) time; the encoding in which the string is most compact
//返回指定编码的NSData对象
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowLossyConversion:(BOOL)lossy; // External representation
//返回指定编码的NSData对象
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding; // External representation
//判断是否可以无损转化编码
- (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding;
/* Methods to convert NSString to a NULL-terminated cString using the specified encoding. Note, these are the "new" cString methods, and are not deprecated like the older cString methods which do not take encoding arguments.
*/
//char编码转换
- (__strong const char *)cStringUsingEncoding:(NSStringEncoding)encoding NS_RETURNS_INNER_POINTER; // "Autoreleased"; NULL return if encoding conversion not possible; for performance reasons, lifetime of this should not be considered longer than the lifetime of the receiving string (if the receiver string is freed, this might go invalid then, before the end of the autorelease scope)
//C字符串这边吗转化是否成功
- (BOOL)getCString:(char *)buffer maxLength:(NSUInteger)maxBufferCount encoding:(NSStringEncoding)encoding; // NO return if conversion not possible due to encoding errors or too small of a buffer. The buffer should include room for maxBufferCount bytes; this number should accomodate the expected size of the return value plus the NULL termination character, which this method adds. (So note that the maxLength passed to this method is one more than the one you would have passed to the deprecated getCString:maxLength:.)
/* Use this to convert string section at a time into a fixed-size buffer, without any allocations. Does not NULL-terminate.
buffer is the buffer to write to; if NULL, this method can be used to computed size of needed buffer.
maxBufferCount is the length of the buffer in bytes. It's a good idea to make sure this is at least enough to hold one character's worth of conversion.
usedBufferCount is the length of the buffer used up by the current conversion. Can be NULL.
encoding is the encoding to convert to.
options specifies the options to apply.
range is the range to convert.
leftOver is the remaining range. Can be NULL.
YES return indicates some characters were converted. Conversion might usually stop when the buffer fills,
but it might also stop when the conversion isn't possible due to the chosen encoding.
*/
//指定缓存区转换
- (BOOL)getBytes:(void *)buffer maxLength:(NSUInteger)maxBufferCount usedLength:(NSUInteger *)usedBufferCount encoding:(NSStringEncoding)encoding options:(NSStringEncodingConversionOptions)options range:(NSRange)range remainingRange:(NSRangePointer)leftover;
/* These return the maximum and exact number of bytes needed to store the receiver in the specified encoding in non-external representation. The first one is O(1), while the second one is O(n). These do not include space for a terminating null.
*/
//字符串编码时需要用的字节长度
- (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc; // Result in O(1) time; the estimate may be way over what's needed. Returns 0 on error (overflow)
//字符串编码时需要用到最大字节长度
- (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc; // Result in O(n) time; the result is exact. Returns 0 on error (cannot convert to specified encoding, or overflow)
FormC 指示使用完全规范化分解对 Unicode 字符串进行规范化,然后将序列替换为其原复合字符(如果可能)。FormD 指示使用完全规范化分解对 Unicode 字符串进行规范化。FormKC 指示使用完全兼容性分解对 Unicode 字符串进行规范化,然后将序列替换为其原复合字符(如果可能)。FormKD 指示使用完全兼容性分解对 Unicode 字符串进行规范化。- (NSString *)decomposedStringWithCanonicalMapping; Unicode范式D标准化
//Unicode范式D标准化
@property (readonly, copy) NSString *decomposedStringWithCanonicalMapping;
//Unicode范式C标准化
@property (readonly, copy) NSString *precomposedStringWithCanonicalMapping;
//Unicode范式KD标准化
@property (readonly, copy) NSString *decomposedStringWithCompatibilityMapping;
//Unicode范式KC标准化
@property (readonly, copy) NSString *precomposedStringWithCompatibilityMapping;
/* Returns a string with the character folding options applied. theOptions is a mask of compare flags with *InsensitiveSearch suffix.
*/
//本地化字符串折叠
- (NSString *)stringByFoldingWithOptions:(NSStringCompareOptions)options locale:(NSLocale *)locale NS_AVAILABLE(10_5, 2_0);
/* Replace all occurrences of the target string in the specified range with replacement. Specified compare options are used for matching target. If NSRegularExpressionSearch is specified, the replacement is treated as a template, as in the corresponding NSRegularExpression methods, and no other options can apply except NSCaseInsensitiveSearch and NSAnchoredSearch.
*/
//字符串指定区域段替换
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange NS_AVAILABLE(10_5, 2_0);
/* Replace all occurrences of the target string with replacement. Invokes the above method with 0 options and range of the whole string.
*/
//字符串替换
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement NS_AVAILABLE(10_5, 2_0);
/* Replace characters in range with the specified string, returning new string.
*/
//指定区域段字符串替换
- (NSString *)stringByReplacingCharactersInRange:(NSRange)range withString:(NSString *)replacement NS_AVAILABLE(10_5, 2_0);
//转化为char
@property (readonly) __strong const char *UTF8String NS_RETURNS_INNER_POINTER; // Convenience to return null-terminated UTF8 representation
/* User-dependent encoding who value is derived from user's default language and potentially other factors. The use of this encoding might sometimes be needed when interpreting user documents with unknown encodings, in the absence of other hints. This encoding should be used rarely, if at all. Note that some potential values here might result in unexpected encoding conversions of even fairly straightforward NSString content --- for instance, punctuation characters with a bidirectional encoding.
*/
//默认C字符串编码
+ (NSStringEncoding)defaultCStringEncoding; // Should be rarely used
//当前编码值
+ (const NSStringEncoding *)availableStringEncodings;
//编码名称
+ (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding;
/*** Creation methods ***/
/* In general creation methods in NSString do not apply to subclassers, as subclassers are assumed to provide their own init methods which create the string in the way the subclass wishes. Designated initializers of NSString are thus init and initWithCoder:.
*/
//指定缓冲区,编码和字节长度初始化NSString对象
- (instancetype)initWithCharactersNoCopy:(unichar *)characters length:(NSUInteger)length freeWhenDone:(BOOL)freeBuffer; /* "NoCopy" is a hint */
//指定unichar字符,字符长度初始化NSString
- (instancetype)initWithCharacters:(const unichar *)characters length:(NSUInteger)length;
//char转化为NSString对象
- (instancetype)initWithUTF8String:(const char *)nullTerminatedCString;
//指定字符串初始化NSString对象
- (instancetype)initWithString:(NSString *)aString;
//格式化对个字符串初始化NSString对象
- (instancetype)initWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
//本地化格式化多个字符串初始化NSString对象
- (instancetype)initWithFormat:(NSString *)format arguments:(va_list)argList NS_FORMAT_FUNCTION(1,0);
//本地化格式化多个字符串初始化NSStringd对象
- (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ... NS_FORMAT_FUNCTION(1,3);
//本地化格式化字符串初始化NSStringd对象
- (instancetype)initWithFormat:(NSString *)format locale:(id)locale arguments:(va_list)argList NS_FORMAT_FUNCTION(1,0);
//指定编码转化NSData数据
- (instancetype)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding;
//指定编码和字节数初始化NSString对象
- (instancetype)initWithBytes:(const void *)bytes length:(NSUInteger)len encoding:(NSStringEncoding)encoding;
//指定缓冲区,编码和字节数初始化NSString对象
- (instancetype)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)len encoding:(NSStringEncoding)encoding freeWhenDone:(BOOL)freeBuffer; /* "NoCopy" is a hint */
//初始化空string对象
+ (instancetype)string;
//初始化string对象
+ (instancetype)stringWithString:(NSString *)string;
//返回指定长度unichar的C字符串
+ (instancetype)stringWithCharacters:(const unichar *)characters length:(NSUInteger)length;
//转化C字符串为UTF8串
+ (instancetype)stringWithUTF8String:(const char *)nullTerminatedCString;
//格式化初始化NSString对象,自动释放内存
+ (instancetype)stringWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
//本地化格式化初始化NSString对象,自动释放内存
+ (instancetype)localizedStringWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
//指定编码初始化c字符串,需要手动释放内存
- (instancetype)initWithCString:(const char *)nullTerminatedCString encoding:(NSStringEncoding)encoding;
//指定编码初始化C字符串,自动释放内存
+ (instancetype)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc;
/* These use the specified encoding. If nil is returned, the optional error return indicates problem that was encountered (for instance, file system or encoding errors).
*/
//指定编码读取URL地址数据转化为字符串,需要手动释放内存(已知编码)
- (instancetype)initWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error;
//指定编码读取FILE地址数据转化为字符串,需要手动释放内存(已知编码)
- (instancetype)initWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error;
//指定编码读取URL地址数据转化为字符串,自动释放内存(已知编码)
+ (instancetype)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error;
//指定编码读取FILE地址数据转化为字符串,自动释放内存(已知编码)
+ (instancetype)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error;
/* These try to determine the encoding, and return the encoding which was used. Note that these methods might get "smarter" in subsequent releases of the system, and use additional techniques for recognizing encodings. If nil is returned, the optional error return indicates problem that was encountered (for instance, file system or encoding errors).
*/
//指定编码读取URL地址数据转化为字符串,需要手动释放内存(未知编码)
- (instancetype)initWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc error:(NSError **)error;
//指定编码读取FILE地址数据转化为字符串,需要手动释放内存(未知编码)
- (instancetype)initWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc error:(NSError **)error;
//指定编码读取URL地址数据转化为字符串,自动释放内存(未知编码)
+ (instancetype)stringWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc error:(NSError **)error;
//指定编码读取FILE地址数据转化为字符串,自动释放内存(未知编码)
+ (instancetype)stringWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc error:(NSError **)error;
/* Write to specified url or path using the specified encoding. The optional error return is to indicate file system or encoding errors.
*/
//指定编码把数据写入文件
- (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error;
//指定编码把数据写入文件
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error;
@end
//可变字符串
@interface NSMutableString : NSString
/* NSMutableString primitive (funnel) method. See below for the other mutation methods.
*/
//使用aString替换range指定的区域段
- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)aString;
@end
@interface NSMutableString (NSMutableStringExtensionMethods)
//以索引loc为起始位置插入aString
- (void)insertString:(NSString *)aString atIndex:(NSUInteger)loc;
//删除指定区域段字符
- (void)deleteCharactersInRange:(NSRange)range;
//追加字符串aString
- (void)appendString:(NSString *)aString;
//追加对个字符串(格式化)
- (void)appendFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
//设置新的aString
- (void)setString:(NSString *)aString;
/* In addition to these two, NSMutableString responds properly to all NSString creation methods.
*/
//初始化一个容量为capacity的字符串,需要手动释放内存
- (NSMutableString *)initWithCapacity:(NSUInteger)capacity;
//初始化一个容量为capacity的字符串,自动释放内存(暂且分配指定容量,用于内存优化,可以大于设置的内容)
+ (NSMutableString *)stringWithCapacity:(NSUInteger)capacity;
/* This method replaces all occurrences of the target string with the replacement string, in the specified range of the receiver string, and returns the number of replacements. NSBackwardsSearch means the search is done from the end of the range (the results could be different); NSAnchoredSearch means only anchored (but potentially multiple) instances will be replaced. NSLiteralSearch and NSCaseInsensitiveSearch also apply. NSNumericSearch is ignored. Use NSMakeRange(0, [receiver length]) to process whole string. If NSRegularExpressionSearch is specified, the replacement is treated as a template, as in the corresponding NSRegularExpression methods, and no other options can apply except NSCaseInsensitiveSearch and NSAnchoredSearch.
*/
//指定限制条件(大小忽略等)指定区域段中的replacement替换成target
- (NSUInteger)replaceOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange;
@end
@interface NSString (NSStringEncodingDetection)
/*
This API is used to detect the string encoding of a given raw data. It can also do lossy string conversion. It converts the data to a string in the detected string encoding. The data object contains the raw bytes, and the option dictionary contains the hints and parameters for the analysis. The opts dictionary can be nil. If the string parameter is not NULL, the string created by the detected string encoding is returned. The lossy substitution string is emitted in the output string for characters that could not be converted when lossy conversion is enabled. The usedLossyConversion indicates if there is any lossy conversion in the resulted string. If no encoding can be detected, 0 is returned.
The possible items for the dictionary are:
1) an array of suggested string encodings (without specifying the 3rd option in this list, all string encodings are considered but the ones in the array will have a higher preference; moreover, the order of the encodings in the array is important: the first encoding has a higher preference than the second one in the array)
2) an array of string encodings not to use (the string encodings in this list will not be considered at all)
3) a boolean option indicating whether only the suggested string encodings are considered
4) a boolean option indicating whether lossy is allowed
5) an option that gives a specific string to substitude for mystery bytes
6) the current user's language
7) a boolean option indicating whether the data is generated by Windows
If the values in the dictionary have wrong types (for example, the value of NSStringEncodingDetectionSuggestedEncodingsKey is not an array), an exception is thrown.
If the values in the dictionary are unknown (for example, the value in the array of suggested string encodings is not a valid encoding), the values will be ignored.
*/
//NSData转化为NSString 有可选opts字典,是否允许有损失,返回一个NSStringEncoding类型
//下面有七种不同的opts选项
+ (NSStringEncoding)stringEncodingForData:(NSData *)data
encodingOptions:(NSDictionary *)opts
convertedString:(NSString **)string
usedLossyConversion:(BOOL *)usedLossyConversion NS_AVAILABLE(10_10, 8_0);
@end
/*
The following keys may be used in the option dictionary.
*/
// NSArray of NSNumbers which contain NSStringEncoding values; if this key is not present in the dictionary, all encodings are weighted the same
FOUNDATION_EXPORT NSString * const NSStringEncodingDetectionSuggestedEncodingsKey NS_AVAILABLE(10_10, 8_0);
// NSArray of NSNumbers which contain NSStringEncoding values; if this key is not present in the dictionary, all encodings are considered
FOUNDATION_EXPORT NSString * const NSStringEncodingDetectionDisallowedEncodingsKey NS_AVAILABLE(10_10, 8_0);
// NSNumber boolean value; if this key is not present in the dictionary, the default value is NO
FOUNDATION_EXPORT NSString * const NSStringEncodingDetectionUseOnlySuggestedEncodingsKey NS_AVAILABLE(10_10, 8_0);
// NSNumber boolean value; if this key is not present in the dictionary, the default value is YES
FOUNDATION_EXPORT NSString * const NSStringEncodingDetectionAllowLossyKey NS_AVAILABLE(10_10, 8_0);
// NSNumber boolean value; if this key is not present in the dictionary, the default value is NO
FOUNDATION_EXPORT NSString * const NSStringEncodingDetectionFromWindowsKey NS_AVAILABLE(10_10, 8_0);
// NSString value; if this key is not present in the dictionary, the default value is U+FFFD
FOUNDATION_EXPORT NSString * const NSStringEncodingDetectionLossySubstitutionKey NS_AVAILABLE(10_10, 8_0);
// NSString value; ISO language code; if this key is not present in the dictionary, no such information is considered
FOUNDATION_EXPORT NSString * const NSStringEncodingDetectionLikelyLanguageKey NS_AVAILABLE(10_10, 8_0);
@interface NSString (NSExtendedStringPropertyListParsing)
/* These methods are no longer recommended since they do not work with property lists and strings files in binary plist format. Please use the APIs in NSPropertyList.h instead.
*/
//字符串转化为属性列表
- (id)propertyList;
//字符串转化为字典
- (NSDictionary *)propertyListFromStringsFileFormat;
@end
@interface NSString (NSStringDeprecated)
/* The following methods are deprecated and will be removed from this header file in the near future. These methods use [NSString defaultCStringEncoding] as the encoding to convert to, which means the results depend on the user's language and potentially other settings. This might be appropriate in some cases, but often these methods are misused, resulting in issues when running in languages other then English. UTF8String in general is a much better choice when converting arbitrary NSStrings into 8-bit representations. Additional potential replacement methods are being introduced in NSString as appropriate.
*/
//转化为C字符串
- (const char *)cString NS_RETURNS_INNER_POINTER NS_DEPRECATED(10_0, 10_4, 2_0, 2_0);
//非无损转化为C字符串
- (const char *)lossyCString NS_RETURNS_INNER_POINTER NS_DEPRECATED(10_0, 10_4, 2_0, 2_0);
//返回转化C字符串后的长度
- (NSUInteger)cStringLength NS_DEPRECATED(10_0, 10_4, 2_0, 2_0);
//转化为C字符串对象
- (void)getCString:(char *)bytes NS_DEPRECATED(10_0, 10_4, 2_0, 2_0);
//制定缓冲区转化为C字符串对象
- (void)getCString:(char *)bytes maxLength:(NSUInteger)maxLength NS_DEPRECATED(10_0, 10_4, 2_0, 2_0);
//指定缓冲区转化C字符串对象
- (void)getCString:(char *)bytes maxLength:(NSUInteger)maxLength range:(NSRange)aRange remainingRange:(NSRangePointer)leftoverRange NS_DEPRECATED(10_0, 10_4, 2_0, 2_0);
//以原子方式数据写入文件
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile NS_DEPRECATED(10_0, 10_4, 2_0, 2_0);
//以原子方式数据写入指定URL
- (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atomically NS_DEPRECATED(10_0, 10_4, 2_0, 2_0);
//读取FILE地址数据,需要手动释放内存
- (id)initWithContentsOfFile:(NSString *)path NS_DEPRECATED(10_0, 10_4, 2_0, 2_0);
//读取URL地址数据,自动释放内存
- (id)initWithContentsOfURL:(NSURL *)url NS_DEPRECATED(10_0, 10_4, 2_0, 2_0);
//读取FILE地址数据,需要手动释放内存
+ (id)stringWithContentsOfFile:(NSString *)path NS_DEPRECATED(10_0, 10_4, 2_0, 2_0);
//读取URL地址数据,自动释放内存
+ (id)stringWithContentsOfURL:(NSURL *)url NS_DEPRECATED(10_0, 10_4, 2_0, 2_0);
//指定缓冲区,字节长度初始化CSting,需要手动释放内存
- (id)initWithCStringNoCopy:(char *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)freeBuffer NS_DEPRECATED(10_0, 10_4, 2_0, 2_0);
//指定字节长度初始化CSting ,需要手动释放内存
- (id)initWithCString:(const char *)bytes length:(NSUInteger)length NS_DEPRECATED(10_0, 10_4, 2_0, 2_0);
//初始化CSting ,需要手动释放内存
- (id)initWithCString:(const char *)bytes NS_DEPRECATED(10_0, 10_4, 2_0, 2_0);
//指定字节长度初始化CSti
+ (id)stringWithCString:(const char *)bytes length:(NSUInteger)length NS_DEPRECATED(10_0, 10_4, 2_0, 2_0);
//初始化CSting ,自动释放内存
+ (id)stringWithCString:(const char *)bytes NS_DEPRECATED(10_0, 10_4, 2_0, 2_0);
/* This method is unsafe because it could potentially cause buffer overruns. You should use -getCharacters:range: instead.
*/
//多位编码转换
- (void)getCharacters:(unichar *)buffer;
@end
enum {
NSProprietaryStringEncoding = 65536 /* Installation-specific encoding */
};
/* The rest of this file is bookkeeping stuff that has to be here. Don't use this stuff, don't refer to it.
*/
#if !defined(_OBJC_UNICHAR_H_)
#define _OBJC_UNICHAR_H_
#endif
#define NS_UNICHAR_IS_EIGHT_BIT 0
@interface NSSimpleCString : NSString {
@package
char *bytes;
int numBytes;
#if __LP64__
int _unused;
#endif
}
@end
@interface NSConstantString : NSSimpleCString
@end
#if __LP64__
#else
extern void *_NSConstantStringClassReference;
#endif