数组-NSArray

只能存储OC对象

初始化

NSArray *a1 = [NSArray new];
NSArray *a2 = [NSArray array];
都没有意义,这样创建出来的元素个数为0



NSArray *a3 = [NSArray arrayWith Objects:, , , ,nil];常用此方法
NSArray *a4 = @[, , , , , ,];此方法后面不要加nil

可以用%@直接将NSArray输出

取值

- (ObjectType)objectAtIndex:(NSUInteger)index;
直接下标访问

常用方法

  • 数量
@property (readonly) NSUInteger count;
  • 判断是否含有该元素
- (BOOL)containsObject:(ObjectType)anObject;
  • 首尾元素
@property (nullable, nonatomic, readonly) ObjectType firstObject 
API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
@property (nullable, nonatomic, readonly) ObjectType lastObject;
  • 寻找某元素第一次出现的下标,如果没有找到返回的是NSUInteger的最大值
- (NSUInteger)indexOfObject:(ObjectType)anObject;
  • 使用block遍历
- (void)enumerateObjectsUsingBlock:(void (NS_NOESCAPE ^)
(ObjectType obj, NSUInteger idx, BOOL *stop))block 
API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
如果想停止遍历,将stop的值改为YES
  • 连接NSArray中的字符串
- (NSString *)componentsJoinedByString:(NSString *)separator;
  • 分隔NSString中的字符串
NSString *string = @"apple,orange,banana";
NSArray *array = [string componentsSeparatedByString:@","];
  • 保存到磁盘
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile A
PI_DEPRECATED_WITH_REPLACEMENT("writeToURL:error:", macos(10.0, API_TO_BE_DEPRECATED), ios(2.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED));
- (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atomically 
API_DEPRECATED_WITH_REPLACEMENT("writeToURL:error:", macos(10.0, API_TO_BE_DEPRECATED), ios(2.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED));
  • 从磁盘读取
+ (nullable NSArray<ObjectType> *)arrayWithContentsOfFile:(NSString *)path API_DEPRECATED_WITH_REPLACEMENT("arrayWithContentsOfURL:error:", macos(10.0, API_TO_BE_DEPRECATED), ios(2.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED));
+ (nullable NSArray<ObjectType> *)arrayWithContentsOfURL:(NSURL *)url API_DEPRECATED_WITH_REPLACEMENT("arrayWithContentsOfURL:error:", macos(10.0, API_TO_BE_DEPRECATED), ios(2.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED));


NSMutableArray-NSArray动态版

  • 添加元素
- (void)addObject:(ObjectType)anObject;普通添加一个元素
- (void)addObjectsFromArray:(NSArray<ObjectType> *)otherArray;把一个数组都加进去
- (void)insertObject:(ObjectType)anObject atIndex:(NSUInteger)index;指定位置插入一个元素
  • 删除
- (void)removeObject:(ObjectType)anObject;删除指定的值
- (void)removeObjectAtIndex:(NSUInteger)index;删除下标的值
- (void)removeAllObjects;删除所有 
- (void)removeObject:(ObjectType)anObject inRange:(NSRange)range;删除范围
- (void)removeLastObject;

字符串-NSString

初始化

NSString *str1 = [[NSString alloc] init];
NSString *str1 = [NSString new];
NSString *str2 = [NSString string];
NSString *str3 = @"";

打印的时候%@ 打印指针变量指向的对象。 %p 打印的是指针变量的值

恒定性

  • 字符串对象存在常量区(数据段)
NSString *str3 = @"jack";
  • 字符串存在堆区
NSString *str1 = [[NSString alloc] init];
NSString *str1 = [NSString new];
NSString *str2 = [NSString string];
  • 在内存中创建一个字符串对象后,这个字符串对象的内容就无法改变

重新为字符串指针初始化值的时候并没有改原来地址的字符串对象,而是重新创建一个字符串对象,再将这个值给指针

  • 当系统准备要在内存中创建字符串对象的时候,会先检查呢困中是否有相同内容的字符串对象。如果有,直接指向,没有则重新创建


常用方法


  • 将C语言中的字符串转换为OC字符串对象
+ (nullable instancetype)stringWithUTF8String:(const char *)nullTerminatedCString
  • 将OC字符串转换为OC字符串对象
@property (nullable, readonly) const char *UTF8String NS_RETURNS_INNER_POINTER;        
// Convenience to return null-terminated UTF8 representation

const char *a = str.UTF8String;
  • 拼接字符串
+ (instancetype)stringWithFormat:(NSString *)format, ...

int age = 10;
NSString *str = [NSString stringWithFormat:@"我的年龄是%d",age];


str = 我的年龄是10
Program ended with exit code: 0
  • 字符串长度
@property (readonly) NSUInteger length;//NSUInteger本质上是ulong


NSString *str = @"你好hello";
NSUInteger len = [str length];
NSLog(@"len = %lu", len);
    
    
len = 7
Program ended with exit code: 0
  • 得到对应下标字符
- (unichar)characterAtIndex:(NSUInteger)index;//typedef unsigned short unichar;
输出用%C,不是%c
  • 判断字符串是否相等
- (BOOL)isEqualToString:(NSString *)aString;

==只能用来判断基本类型,不能判断引用类型。指针类型判断的也是值(指向的地址)


  • 比较大小,可以使用int接收结果
- (NSComparisonResult)compare:(NSString *)string;
typedef NS_CLOSED_ENUM(NSInteger, NSComparisonResult) {
    NSOrderedAscending = -1L,//<
    NSOrderedSame,
    NSOrderedDescending//>
};

- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask;
NSCaseInsensitiveSearch = 1,
    NSLiteralSearch = 2,                /* Exact character-by-character equivalence */
    NSBackwardsSearch = 4,                /* Search from end of source string */
    NSAnchoredSearch = 8,                /* Search is limited to start (or end, if NSBackwardsSearch) of source string */
    NSNumericSearch = 64,                /* Added in 10.2; Numbers within strings are compared using numeric value, that is, Foo2.txt < Foo7.txt < Foo25.txt; only applies to compare methods, not find */
    NSDiacriticInsensitiveSearch 
    API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 128, 
    /* If specified, ignores diacritics (o-umlaut == o) */
    NSWidthInsensitiveSearch 
    API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 256, 
    /* If specified, ignores width differences ('a' == UFF41) */
    NSForcedOrderingSearch 
    API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 512, 
    /* If specified, comparisons are forced to return either NSOrderedAscending or NSOrderedDescending if the strings are equivalent but not strictly equal, for stability when sorting (e.g. "aaa" > "AAA" with NSCaseInsensitiveSearch specified) */
    NSRegularExpressionSearch 
    API_AVAILABLE(macos(10.7), ios(3.2), watchos(2.0), tvos(9.0)) = 1024    
    /* Applies to rangeOfString:..., stringByReplacingOccurrencesOfString:..., and replaceOccurrencesOfString:... methods only; the search string is treated as an ICU-compatible regular expression; if set, no other options can apply except NSCaseInsensitiveSearch and NSAnchoredSearch */
  • 将字符串内容写入到磁盘上的某个文件中
- (BOOL)writeToFile:(NSString *)path 
    //文件路径
    atomically:(BOOL)useAuxiliaryFile 
    //YES 先将内容写到临时文件里,成功后再写到指定目录,安全,效率低
    //NO 直接将内容写到指定文件, 不安全,效率高
    encoding:(NSStringEncoding)enc 
    //指定写入使用的编码一般UTF8,NSUTF8StringEncoding
    error:(NSError **)error;
    //二级指针,传入NSError指针的地址
    
  返回值为BOLL类型,返回是否成功写入
  • 从指定的文件中读取字符串
+ (nullable instancetype)stringWithContentsOfFile:(NSString *)path 
encoding:(NSStringEncoding)enc 
error:(NSError **)error;
  • 使用URL来读取字符串数据
  • 优势:既可以读本地磁盘文件,又可以读网页文件、发FTP服务器上的文件
  • 不同类型的URL地址写法不同
  • 本地磁盘文件:file:///Users/admin/Desktop/XXX.xxx
  • 网页地址;http://gz.xxxx.cn
  • FTP文件:ftp://server.xxx.cn/xx/xxx.xx
  • 将不同类型的地址封装在NSURL对象中
  • NSURL *u1 = [NSURL URLWithString:@"https://www.bilibili.com/video/BV1NJ411T78u?p=167&spm_id_from=pageDriver&vd_source=4852f0fd2838c9dc71dd11e6d14e8735"];
    NSError *err;
    NSString *str = [NSString stringWithContentsOfURL:u1 encoding:NSUTF8StringEncoding error:&err];
        
    NSLog(@"%@", str);
NSURL *u1 = [NSURL URLWithString:@"file:///Users/admin/Desktop/abc.txt"];
NSString *str = @"hello";
[str compare:str options: 1];
NSError *err;
BOOL res = [str writeToURL:u1 atomically:NO encoding:NSUTF8StringEncoding error:&err];
if(res == YES){
    NSLog(@"写入成功");
}else{
    NSLog(@"失败");
    NSLog(@"%@",err.localizedFailureReason);
}
  • 比较字符串前缀
- (BOOL)hasPrefix:(NSString *)str;
  • 比较字符串结尾
- (BOOL)hasSuffix:(NSString *)str;
  • 在主串中搜索str的范围
- (NSRange)rangeOfString:(NSString *)searchString;

typedef struct NS_SWIFT_SENDABLE _NSRange {
    NSUInteger location;    str在字符串中第一次出现的下标
    NSUInteger length;      匹配的长度
} NSRange;

看是否能找到直接看length即可(是否为0)

- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask;
options可以输入别的,如:从后往前搜等。

NSCaseInsensitiveSearch = 1,
    NSLiteralSearch = 2,                /* Exact character-by-character equivalence */
    NSBackwardsSearch = 4,                /* Search from end of source string */
    NSAnchoredSearch = 8,                
    /* Search is limited to start (or end, if NSBackwardsSearch) of source string */
    NSNumericSearch = 64,                
    /* Added in 10.2; Numbers within strings are compared using numeric value, that is, Foo2.txt < Foo7.txt < Foo25.txt; only applies to compare methods, not find */
    NSDiacriticInsensitiveSearch 
    API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 128, 
    /* If specified, ignores diacritics (o-umlaut == o) */
    NSWidthInsensitiveSearch 
    API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 256, 
    /* If specified, ignores width differences ('a' == UFF41) */
    NSForcedOrderingSearch 
    API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 512, 
    /* If specified, comparisons are forced to return either NSOrderedAscending or NSOrderedDescending if the strings are equivalent but not strictly equal, for stability when sorting (e.g. "aaa" > "AAA" with NSCaseInsensitiveSearch specified) */
    NSRegularExpressionSearch 
    API_AVAILABLE(macos(10.7), ios(3.2), watchos(2.0), tvos(9.0)) = 1024    
    /* Applies to rangeOfString:..., stringByReplacingOccurrencesOfString:..., and replaceOccurrencesOfString:... methods only; the search string is treated as an ICU-compatible regular expression; if set, no other options can apply except NSCaseInsensitiveSearch and NSAnchoredSearch */
  • 字符串中截取
- (NSString *)substringFromIndex:(NSUInteger)from;从指定下标开始截取
- (NSString *)substringToIndex:(NSUInteger)to;从第0个开始截取指定的个数
- (NSString *)substringWithRange:(NSRange)range;截取指定的范围,idx,len
  • 字符串替换
NSString *str = @"hello";
str = [str stringByReplacingOccurrencesOfString:@"o" withString:@"llll"];  还可以替换为空串
  • 字符串转换为其他类型
@property (readonly) double doubleValue;
@property (readonly) float floatValue;
@property (readonly) int intValue;
@property (readonly) NSInteger integerValue 
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
@property (readonly) long long longLongValue 
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
@property (readonly) BOOL boolValue 
API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.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.
  • 去掉字符串前后东西
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set;去空格
stringByTrimmingCharactersInSet:[NSCharacterSet lowercaseLetterCharacterSet];去小写
stringByTrimmingCharactersInSet:[NSCharacterSet uppercaseLetterCharacterSet];去大写

NSMutableString-NSString的优化版

存储在NSSMutableString对象中的字符串数据可以更改。具备可变性

直接可以改存储在其中的字符串数据,不会新创建对象

初始化

NSMutableString *str = [NSMutableString new];
NSMutableString *str = @"jack"; 这样不行,右边父类,左边子类

追加字符串

- (void)appendFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); 
- (void)appendString:(NSString *)aString;


NSDictionary

以键值对形式存储数据。一旦创建无法动态新增,修改和删除

  • 建:只能是遵守了NSCoping协议的对象,而NSString就是遵守了这个协议
  • 值:只能是OC对象

一般创建方式

NSDictionary *mydict = [NSDictionary dictionaryWithObjectsAndKeys:@"jack",@"name", nil];
先写值,在写键

NSDictionary *mydict = @{@"name":@"jack", xxx:xx,,,,};

访问

mydict[@"name"]
[mydict objectForKey:@"name"]

值不存在就是nil

取集合

@property (readonly, copy) NSArray<KeyType> *allKeys;
@property (readonly, copy) NSArray<ObjectType> *allValues;

遍历

NSDictionary *mydict = @{@"name":@"jack"};
for in 遍历
for(id a in mydict){
    NSLog(@"%@, %@", a, mydict[a]);
}

block遍历
[mydict enumerateKeysAndObjectsUsingBlock:
^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
     NSLog(@"%@->%@", key, obj);
}];

NSMutableDictionary

以键值对形式存储数据。一旦创建可以动态新增,修改和删除

  • 建:只能是遵守了NSCoping协议的对象,而NSString就是遵守了这个协议
  • 值:只能是OC对象

添加

NSDictionary *mydict = @{@"name":@"jack"};
NSMutableDictionary *mutabledict = [NSMutableDictionary dictionaryWithDictionary:mydict];
mutabledict[@"ggg"] = @"rose";
[mutabledict setObject:@"广州XXX" forKey:@"留仙大道"];

删除

- (void)removeObjectForKey:(KeyType)aKey;删除特定的
- (void)removeAllObjects;删除所有的

持久化

  • 存入磁盘
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile API_DEPRECATED_WITH_REPLACEMENT("writeToURL:error:", macos(10.0, API_TO_BE_DEPRECATED), ios(2.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED));
- (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atomically API_DEPRECATED_WITH_REPLACEMENT("writeToURL:error:", macos(10.0, API_TO_BE_DEPRECATED), ios(2.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED)); // the atomically flag is ignored if url of a type that cannot be written atomically.
  • 从磁盘取出
NSMutableDictionary *newdict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/Users/admin/Desktop/dict.plist"];

NSSet

  • 个数
@property (readonly) NSUInteger count;
  • 返回所有对象
@property (readonly, copy) NSArray<ObjectType> *allObjects;
  • 返回任意对象
- (nullable ObjectType)anyObject;
  • 判断是否含有该元素
- (BOOL)containsObject:(ObjectType)anObject;
  • 判断两个集合是否有交集
- (BOOL)intersectsSet:(NSSet<ObjectType> *)otherSet;
  • 判断两个集合是否完全匹配
- (BOOL)isEqualToSet:(NSSet<ObjectType> *)otherSet;
  • 判断当前集合是否是该集合的子集
- (BOOL)isSubsetOfSet:(NSSet<ObjectType> *)otherSet;

NSMutableSet

  • 当前集合减去该集合的元素
- (void)minusSet:(NSSet<ObjectType> *)otherSet;
  • 给当前集合和该集合取交集
- (void)intersectSet:(NSSet<ObjectType> *)otherSet;
  • 并集
- (void)unionSet:(NSSet<ObjectType> *)otherSet;
  • 当前集合设置为该集合中的内容
- (void)setSet:(NSSet<ObjectType> *)otherSet;
  • 删除
- (void)removeAllObjects;
- (void)removeObject:(ObjectType)object;
- (void)removeObject:(ObjectType)object;



CGPoint和NSPoint-点的位置

CGPoint {
    CGFloat x;
    CGFloat y;
};

typedef CGPoint NSPoint;

初始化

CGPointMake(CGFloat x, CGFloat y)
{
  CGPoint p; p.x = x; p.y = y; return p;
}

NS_INLINE NSPoint NSMakePoint(CGFloat x, CGFloat y) {
    NSPoint p;
    p.x = x;
    p.y = y;
    return p;
}

NSSize/CGSize控件的大小

typedef CGSize NSSize;
struct CGSize {
    CGFloat width;
    CGFloat height;
};


NS_INLINE NSSize NSMakeSize(CGFloat w, CGFloat h) {
    NSSize s;
    s.width = w;
    s.height = h;
    return s;
}


NSSize size = NSMakeSize(2, 3);
CGSize cgsize = CGSizeMake(3, 2);

CGSizeMake(CGFloat width, CGFloat height)
{
  CGSize size; size.width = width; size.height = height; return size;
}

CGRect和MNSRect

  • 保存大小和位置
struct CGRect {
    CGPoint origin;
    CGSize size;
};
typedef struct CF_BOXABLE CGRect CGRect;
typedef CGRect NSRect;


CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
{
  CGRect rect;
  rect.origin.x = x; rect.origin.y = y;
  rect.size.width = width; rect.size.height = height;
  return rect;
}
NS_INLINE NSRect NSMakeRect(CGFloat x, CGFloat y, CGFloat w, CGFloat h) {
    NSRect r;
    r.origin.x = x;
    r.origin.y = y;
    r.size.width = w;
    r.size.height = h;
    return r;
}


封装结构体-NSValue

+ (NSValue *)valueWithPoint:(NSPoint)point;
+ (NSValue *)valueWithSize:(NSSize)size;
+ (NSValue *)valueWithRect:(NSRect)rect;
+ (NSValue *)valueWithEdgeInsets:(NSEdgeInsets)insets API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0));
实例:
NSValue *v1 = [NSValue valueWithRect:nsrect];

@property (readonly) NSPoint pointValue;
@property (readonly) NSSize sizeValue;
@property (readonly) NSRect rectValue;
@property (readonly) NSEdgeInsets edgeInsetsValue API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0));

包装后可以存到集合里

NSDate类-时间处理

  • 得到当前时间
NSDate *date = [NSDate new];
NSLog(@"%@", date);
  • 自定义格式
  • 创建一个格式化对象
  • NSDateFormatter *formatter = [NSDateFormatter new];
  • 指定格式化对象转换的格式
  • formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    formatter.dateFormat = @"yyyy年MM月dd天 HH时mm分ss秒";
    。。。
  • 格式化对象按照指定的格式将日期对象转换
  • NSString *str = [formatter stringFromDate:date];
  • 字符串转换为日期(操作同上)
NSDate *date = [NSDate new];
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = @"yyyy年MM月dd天 HH时mm分ss秒";
NSString *str = @"2023年12月19天 16时48分14秒";
date = [formatter dateFromString:str];
NSLog(@"%@", str);
  • 计算时间
  • 在当前时间加或者减一段时间
  • + (instancetype)dateWithTimeIntervalSinceNow:(NSTimeInterval)secs;
  • 两个时间之差
  • - (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate;
  • 得到日期中的部分数据
  • 法一(同格式部分一样):
  • NSDate *date = [NSDate new];
    NSDateFormatter *formatter = [NSDateFormatter new];
    formatter.dateFormat = @"yyyy"; 年    MM月    dd日。。。。
    NSString *str = [formatter stringFromDate:date];
    NSLog(@"%@", str);
  • 法二:
  • 先创建一个日历对象
  • NSCalendar *calendar = [NSCalendar currentCalendar];
  • 让日历对象从日期对象中取出日期的各个部分
  • - (NSDateComponents *)components:(NSCalendarUnit)unitFlags fromDate:(NSDate *)date;
    
    NSDateComponents * com =  [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth fromDate:date];
    
    NSLog(@"%lu-%lu-%lu-%lu", com.year, com.month, com.day, com.weekday);

NSAttributedString

一种可变字符串,其部分文本具有关联的属性(例如视觉样式、超链接或辅助功能数据)。

初始化

- (instancetype)initWithString:(NSString *)str;
- (instancetype)initWithString:(NSString *)str attributes:(nullable 
NSDictionary<NSString *, id> *)attrs;
- (instancetype)initWithAttributedString:(NSAttributedString *)attrStr;
- (instancetype)initWithString:(NSString *)str;
- (instancetype)initWithString:(NSString *)str attributes:(nullable 
NSDictionary<NSString *, id> *)attrs;
- (instancetype)initWithAttributedString:(NSAttributedString *)attrStr;

第一种使用字符串初始化初始化富文本

第二种使用字符串及属性字典(就是配置富文本的相关属性)初始化富文本

第三种就是用其他富文本初始化富文本

常用操作

  • 为某一范围内文字添加某个属性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
  • 为某一范围内文字添加多个属性(两个API效果与格式一样)
- (void)addAttributes:(NSDictionary<NSString *, id> *)attrs range:(NSRange)range;

- (void)setAttributes:(nullable NSDictionary<NSString *, id> *)attrs 
range:(NSRange)range;
  • 移除某范围内的某个属性(可与添加属性API对照,不在示例)
- (void)removeAttribute:(NSString *)name range:(NSRange)range;
  • 其他部分API(见名知意,可与NSString对照不在赘述)
- (void)replaceCharactersInRange:(NSRange)range withAttributedString:
(NSAttributedString *)attrString;
- (void)insertAttributedString:(NSAttributedString *)attrString 
atIndex:(NSUInteger)loc;
- (void)appendAttributedString:(NSAttributedString *)attrString;
- (void)deleteCharactersInRange:(NSRange)range;
- (void)setAttributedString:(NSAttributedString *)attrString;
- (void)replaceCharactersInRange:(NSRange)range withAttributedString:
(NSAttributedString *)attrString;
- (void)insertAttributedString:(NSAttributedString *)attrString 
atIndex:(NSUInteger)loc;
- (void)appendAttributedString:(NSAttributedString *)attrString;
- (void)deleteCharactersInRange:(NSRange)range;
- (void)setAttributedString:(NSAttributedString *)attrString;
  • 相关可设置属性对照
通过API我们可以知道,对于富文本来说添加单个属性和添加属性字典称为其核心方法,就是一个key对应一个Value,只要能了解各种属性所对应效果就可以随意组合,搞出适合各种需求的封装API。

NSFontAttributeName :字体字号
value值:UIFont类型
NSParagraphStyleAttributeName : 段落样式
value值:NSParagraphStyle类型(其属性如下)
lineSpacing 行间距(具体用法可查看上面的设置行间距API)
paragraphSpacing 段落间距
alignment 对齐方式
firstLineHeadIndent 指定段落开始的缩进像素
headIndent 调整全部文字的缩进像素
NSForegroundColorAttributeName 字体颜色
value值:UIColor类型
NSBackgroundColorAttributeName 背景颜色
value值:UIColor类型
NSObliquenessAttributeName 字体粗倾斜
value值:NSNumber类型
NSExpansionAttributeName 字体加粗
value值:NSNumber类型(比例) 0就是不变 1增加一倍
NSKernAttributeName 字间距
value值:CGFloat类型
NSUnderlineStyleAttributeName 下划线
value值:1或0
NSUnderlineColorAttributeName 下划线颜色
value值:UIColor类型
NSStrikethroughStyleAttributeName 删除线
value值:1或0
NSStrikethroughColorAttributeName 删除线颜色
value值:UIColor类型
NSStrokeColorAttributeName 字体颜色
value值:UIColor类型
NSStrokeWidthAttributeName 字体描边
value值:CGFloat
NSLigatureAttributeName 连笔字
value值:1或0
NSShadowAttributeName 阴影
value值:NSShawdow类型(下面是其属性)
shadowOffset 影子与字符串的偏移量
shadowBlurRadius 影子的模糊程度
shadowColor 影子的颜色
NSTextEffectAttributeName 设置文本特殊效果,目前只有图版印刷效果可用
value值:NSString类型
NSAttachmentAttributeName 设置文本附件
value值:NSTextAttachment类型(没研究过,可自行百度研究)
NSLinkAttributeName 链接
value值:NSURL (preferred) or NSString类型
NSBaselineOffsetAttributeName 基准线偏移
value值:NSNumber类型
NSWritingDirectionAttributeName 文字方向 分别代表不同的文字出现方向
value值:@[@(1),@(2)]
NSVerticalGlyphFormAttributeName 水平或者竖直文本 在iOS没卵用,不支持竖版
value值:1竖直 0水平

-----------------------------------
©著作权归作者所有:来自51CTO博客作者wx638472a9a5de8的原创作品,请联系作者获取转载授权,否则将追究法律责任
NSAttributedString富文本简单介绍和常用方法浅析
https://blog.51cto.com/u_15894905/5892310


NSBundle

// 获得 Bundle 信息
/*
通常指向 xxx.app/ 这个根目录
*/
NSBundle *mainBundle = [NSBundle mainBundle];
// 获取 Bundle 文件路径
NSString *bundlePath = [NSBundle mainBundle].bundlePath;
NSString *resourcePath = [NSBundle mainBundle].resourcePath;
// 获取 Bundle URL 路径
NSURL *bundleUrl = [NSBundle mainBundle].bundleURL;
NSURL *resourceURL = [NSBundle mainBundle].resourceURL;
// 获得 Bundle 目录下的文件路径
NSString *filePath1 = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"txt"];
// 获得 bundle 下子目录 subdirectory 下的文件路径
NSString *filePath2 = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"txt" inDirectory:@"testFolder"];
// 获得 Bundle 目录下的 URL 路径
NSURL *fileUrl1 = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"txt"];
// 获得 bundle 下子目录 subdirectory 下的 URL 路径
NSURL *fileUrl2 = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"txt" subdirectory:@"testFolder"];
// 获取应用程序唯一标识包名
NSString *indentifier = [NSBundle mainBundle].bundleIdentifier;
// 获取应用程序 Info.plist 配置项词典对象实例
NSDictionary *info = [NSBundle mainBundle].infoDictionary;
// 获取某一特定字段的内容
NSString *bundleID = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];