OC常用方法

OC


类对象

<1>一个类是否是另外一个类的子类

- (BOOL)isSubClassofClass:  [xxx class];

<2>一个引用指向的对象是否是某种类型或子类型

- (BOOL)isKindOfClass:[xxx class];

<3>一个引用(实例)指向的对象是否是某种类型

- (BOOL)isMemberOfClass:[xxx class];

方法选择器

<1>某个类是否存在某个方法

- (BOOL)instancesRespondToSelector:@selector(方法名);

<2>强制发送消息

- (id)performSelector:@selector(方法名);

<3>是否可以使用某个方法

- (BOOL)respondsToSelector:(SEL)aSelector;

协议选择器

<1>某个类是否遵守了某个协议

- (BOOL) conformsToProtocol:@protocol(协议名);

NSRange

NSRange是一个结构体,其中location是一个以0为开始的index,length是表示对象的长度。他们都是NSUInteger类型。

typedef struct _NSRange {
    NSUInteger location;
    NSUInteger length;
} NSRange;

<1>字符串内的某处是否包含其他的字符串

- (NSRange)rangeOfString:(NSString *)searchString;
返回一个NSRange struct来告诉你一个与这个字符串相匹配的部分从哪里开始以及匹配上的字符个数

NSString不可变字符串

<1>创建

NSString *str = @”内容”;

<2>格式化创建

+ (instancetype)stringWithFormat:@“%@,%@”,@“内容a”,@“内容b”

<3>从开头分割到某个位置

- (NSString *)substringToIndex:下标

<4>从中间分割到结尾

- (NSString *)substringFromIndex:下标

<5>从中间分割长度x

- (NSString *)substringWithRange:NSMakeRange(下标, 长度)

<6>末尾追加

- (NSString *)stringByAppendingString:@”内容”

<7>按指定格式追加

- (NSString *)stringByAppendingFormat:@”%@ %@”,@”内容a”,@”内容b”`

<8>指定位置替换

- (NSString *)stringByReplacingCharactersInRange:NSMakeRange(下标, 长度) withString:@”内容”

<9>转换从文件读取的数据的编码

NSString *path = @”/Users/apple/Desktop/test.txt”;
+ (nullable instancetype)stringWithContentsOfFile:path encoding:NSUTF8StringEncoding  error:nil

<10>字符串的比较(内容是否相同)

- (BOOL)isEqualToString:@”内容”`

<11>转换为大写字符串

(NSString *)uppercaseString

<12>字符串的比较(比较大小)

- (NSComparisonResult)compare:(NSString *)string;

如果a比b大,返回1,一样返回0,小返回-1

<13>判断创建的字符串内容是否以某个字符开始

- (BOOL)hasPrefix:(NSString *)str;

<14>判断创建的字符串内容是否以某个字符结束

- (BOOL)hasSuffix:(NSString *)str;

<15>把一个字符串通过指定字符串(或者@"\n"等)分割生成一个数组

- (NSArray<NSString *> *)componentsSeparatedByString:(NSString *)separator;

<16>从地址中获取文件名和后缀

NSString * fileName = [path lastPathComponent];

NSMutableString可变字符串

<1>创建

NSMutableString *str = [[NSMutableString alloc]init];`

<2>在指定位置添加内容

- (void)insertString:@”内容” atIndex:下标`

<3>在最后添加内容

- (void)appendString:@”内容”`

<4>在最后添加指定格式内容

- (void)appendFormat:@“%@,%@”,@“内容a”,@“内容b”`

<5>删除

- (void)deleteCharactersInRange:NSMakeRange(下标, 长度)`

<6>替换

- (void)replaceCharactersInRange:NSMakeRange(下标, 长度) withString:@”内容”`

NSNumber基本数据类型类封装

<1>int型

封装+(NSNumber *)numberWithInt:int型数字`

拆封(int)intValue`

<2>char型

封装+(NSNumber *)numberWithChar:’字符’`

拆封(char)charValue`

<3>float型

封装+(NSNumber *)numberWithFloat:float型数字`

拆封(float)floatValue`

<4>double型

封装+(NSNumber *)numberWithDouble:double型数字
拆封(double)doubleValue

<5>BOOL型

封装+(NSNumber *)numberWithBool:YES/NO
拆封(BOOL)doubleValue

NSValue结构体类封装

<1>封装

TRPoint p = {3,4};
结构体赋值valueWithBytes:&p结构体首地址objCType:@encode(TRPoint)

<2>拆封

- (void)getValue:&p2接收的结构体首地址

NSDate时间

<1>得到当前时间

NSDate *date = [[NSDate alloc]init];

<2>得到一个延迟x秒的时间

+ (instancetype)dateWithTimeIntervalSinceNow:30.0f

<3>得到两个时间差

- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate;

<4>得到指定格式的时间,自动转换为系统时区

NSDateFormatter *df = [[NSDateFormatter alloc]init];
df.dateFormat = @”yyyy-MM-dd hh:mm:ss”
(NSString *)df stringFromDate:[[NSDate alloc]init]

NSTimeZone * zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate:date];
NSData * localeTime = [date dateByAddingTimeInterval:interval];

NSArray不可变数组

<1>创建

NSArray *array = @[@“内容a”,(ObjectType)str,@“内容b”];

<2>获得数组长度

.count

<3>通过数组下标获得元素

- (ObjectType)objectAtIndex:(NSUInteger)下标;

<4>获得数组最后一个元素

.lastObject

<5>获得数组第一个元素

.firstObject

<6>获取某个对象在数组的下标,如果数组中不存在该对象,则返回一个垃圾值下标

- (NSUInteger)indexOfObject:@”内容”

<7>OC中数组遍历的三种方式

a for循环

for (int i = 0; i < [stus count]; i++) {
    Students *stu = [stus objectAtIndex:i];
    NSLog(@”%@”, stu);
}

b for快速枚举

//参数1元素的引用 参数2数组或集合名
for (Students *stu2 in stus) {
    NSLog(@”%@”, stu2);
}

c 迭代器遍历

取出数组中元素
自动向下移动一位
//迭代器遍历
//每个数组或者集合相应的迭代器,遍历完会返回一个nil;
NSEnumerator *enumerator = [stus objectEnumerator];
//去数组中取出元素
//并且回自动向下移动一位
Students *st3 = nil;
while (st3 = [enumerator nextObject]) {
    NSLog(@”%@”, st3);
}
- (void)enumerateObjectsUsingBlock:(void (^)(ObjectType obj, NSUInteger idx, BOOL *stop))block
可以同时得到当前数组内容和数组下标

NSArray * array = @[@"a",@"b",@"c"];
[array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSLog(@"%@,%ld",obj,idx);
}];

<7>输出存储自定义类的数组,需要重写description方法,自定义输出格式

-(NSString *)description{
    return [NSString stringWithFormat:@”name:%@ age:%d”, self.name, self.age];
}
否则需要使用NSLog(@”name:%@ age:%i”,stu.name, stu.age);来输出

<8>数组的拷贝

深拷贝 (NSArray *)[[NSArray alloc]initWithArray:要拷贝数组名copyItems:YES]
浅拷贝 (NSArray *)[[NSArray alloc]initWithArray:要拷贝数组名copyItems:NO]

Order数组排序

<1>排序规则

SEL sel = @selector(compare:);

<2>两两比较

- (NSArray<ObjectType> *)sortedArrayUsingSelector:(SEL)comparator

<3>当数组比较的不是基本数据类型,需要重写compare方法

-(NSComparisonResult) compare:(Students *) otherStudent{
//    if((self.age - otherStudent.age) >0)c
//        return NSOrderedDescending;
//    else if ((self.age - otherStudent.age) <0)
//        return NSOrderedAscending;
//    else
//        return NSOrderedSame;
//封装两个int型 调用系统compare方法
    NSNumber *n1 = [NSNumber numberWithInt:self.age];
    NSNumber *n2 = [NSNumber numberWithInt:otherStudent.age]; return [n1 compare:n2];
//追加对姓名进行排序—对字符串进行排序
//    return [self.name compare:otherStudent.name];
}

NSMutableArray可变数组

<1>普通创建

NSMutableArray *mArray =[[NSMutableArray alloc]init];

<2>预定义空间创建

NSMutableArray *mArray2 = [NSMutableArray arrayWithCapacity:19];

<3>初始化创建

NSMutableArray *mArray3 = [NSMutableArray arrayWithObjects:@”内容”, (ObjectType)str, nil];

<4>将不可变数组转化为可变数组

- (id)mutableCopy

<5>添加元素到末尾

- (void)addObject:@”内容”

<6>添加元素到指定位置

- (void)insertObject:@”内容” atIndex:下标

<7>删除末尾

- (void)removeLastObject

<8>删除指定对象

- (void)removeObject:@”内容”

<9>删除指定位置元素

- (void)removeObjectAtIndex:下标

<10>删除所有元素

- (void)removeAllObjects;

<11>修改元素

- (void)replaceObjectAtIndex:下标withObject:@”内容”

NSSet不可变不可重复无序集合(无下标)

(1)每一个对象都有一个hash码,hash码是用来唯一标识对象的。(hash算法)如果hash码相同,就认为两个对象可能向东,hash码不同,一定是两个对象。当对象放入到NSSet集合中,会自动调用对象的hash码进行判断。

(2)当hash码相同时,会自动调用对象的isEqual方法,再次判断对象是否重复,根据方法的返回值决定对象是否重复。

-(NSUInteger)hash{
    NSLog(@“绕过hash算法判断”); 
    return 1;
}

-(BOOL)isEqual:(id)object{
    NSLog(@”isEqual执行了”);
    //a.判断自反值
    if(self == object){
        return YES;
   }
    //b.判断类型是否相同
    if([object isKindOfClass:[Student class]]){
        //c.判断值是否相同_
        Student *otherStudent = object;
        if([self.name isEqualToString:otherStudent.name]&&(self.age == otherStudent.age)){
            return YES;
        }
        else{
            return NO;
        }
    }
    else{
        return NO;

    }
}

NSMutableSet可变不可重复无序集合(无下标)

<1>创建

NSMutableSet *mSet = [NSMutableSet set];
NSMutableSet *mSet2 = [NSMutableSet setWithObjects:@”1”,@”two”, ,nil];

<2>添加元素

- (void)addObject:@”内容”

<3>删除元素

 - (void)removeObject: @”内容”

<4>两个集合的交集

- (void)intersectSet: (NSSet<ObjectType> *)otherSet

<5>两个集合的并集(集合是无序的,所以输出顺序不定)

- (void) unionSet: (NSSet<ObjectType> *)otherSet

<6>根据集合删除另外一个集合中的元素

- (void) minusSet: (NSSet<ObjectType> *)otherSet

NSDictionary字典

<1>创建字典

a创建字典对象(一对出现,value1,key1,value2,key2)

NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys: (id)firstObject,@“key1”,(id)secondObject,@“key2”nil];

b通过数组创建字典

(instancetype)dictionaryWithObjects: (NSArray<ObjectType> *)objects forKeys: (NSArray<ObjectType> *)keys

c通过已有字典创建字典

(instancetype)dictionaryWithDictionary: (NSDictionary<KeyType, ObjectType> *)dict

d快速创建字典

NSDictionary *dict=@{
              @"北京":@[@"东城",@"西城",@"朝阳",@"海淀"],
              @"上海":@[@"静安",@"徐汇",@"浦东"],
              @"广州":@[@"白云",@"越秀",@"天河"]
              };

<2>获取字典中键值对的个数

.count

<3>得到字典中所有的key

- (NSArray<KeyType> *) allKeys

<4>得到字典中所有的value

- (NSArray<ObjectType> *)allValues

<5>通过对象获取关键字值

- (NSArray<KeyType> *)allKeysForObject: (ObjectType)anObject

<6>根据key值得到相应的value值

- (nullable ObjectType) objectForKey: (KeyType)aKey

<7>遍历字典中的元素

NSArray *keys = [dict allKeys];
for (NSString *key in keys) {
    NSString *value = [dict objectForKey:key];
    NSLog(@”key-->%@  value-->%@”,key,value);
}

<8>遍历多重嵌套字典

NSArray *collegekeys = [university allKeys];
for (NSString *collegekey in collegekeys) {
    NSDictionary *college = [university objectForKey:collegekey];
    NSArray *classkeys = [college allKeys];
    for (NSString *classkey in classkeys) {
        NSDictionary *class = [college objectForKey:classkey];
        for (Student *student in class) {
            NSLog(@"name-->%@  age-->%i",student.name,student.age);
        }
    }           
}

NSMutableDictionary可修改字典

<1>创建

a创建空的可修改字典

NSMutableDictionary *dict = [NSMutableDictionary dictionary];

b创建包含预估值的可修改字典

NSMutableDictionary *dict= [NSMutableDictionary dictionaryWithCapacity:18];

c创建初始化可修改字典

NSMutableDictionary *dict= [NSMutableDictionary dictionaryWithObjectsAndKeys:stu,@“1”,stu1,@“2”, nil];

<2> 添加

a添加一个元素

- (void)setValue:(nullable ObjectType)value forKey:(NSString *)key;
mutableDic[@"key"] = @"value";

b添加一个字典

- (void)addEntriesFromDictionary:(NSDictionary<KeyType, ObjectType> *)otherDictionary;

<3> 覆盖一个字典

- (void)setDictionary:(NSDictionary<KeyType, ObjectType> *)otherDictionary;

<4>删除

a删除一个键值对

- (void)removeObjectForKey: (KeyType)aKey

b删除多个键值对

NSArray *keys = @[@"1",@"2"] ;
[dict removeObjectForKey:keys];

<5>清空字典

- (void)removeAllObjects

NSTimer定时器

常见设置及方法

属性

fireDate——>设置定时器的启动时间,常用来管理定时器的启动与停止

//启动定时器
timer.fireDate = [NSDate distantPast];
//停止定时器
timer.fireDate = [NSDate distantFuture];

timeInterval——>只读属性,获取定时器调用间隔时间

tolerance——>因为NSTimer并不完全精准,通过这个值设置误差范围

valid(isValid)——>获取定时器是否有效

userInfo——>获取参数信息

启动定时器

- (void)fire;

销毁定时器

- (void)invalidate;

定时器方法

NSTimeInterval:调用的间隔 target:触发者 selector:触发方法 userInfo:当定时器失效时,由你指定的对象保留和释放该定时器,可以选nil repeats:当YES时,定时器会不断循环直至失效或被释放,当NO时,定时器会循环发送一次就失效 invocation:创建NSInvocation对象并设置触发对象和方法

创建并且会加入循环,不需要手动fire来启动

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
NSInvocation * invo = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:@selector(init)]];
[invo setTarget:self];
[invo setSelector:@selector(myLog)];

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(nullable id)ui repeats:(BOOL)rep 

注意

  1. 参数repeats是指定是否循环执行,YES将循环,NO将只执行一次。
  2. timerWithTimeInterval这两个类方法创建出来的对象如果不用 addTimer: forMode方法手动加入主循环池中,将不会循环执行。并且如果不手动调用fair,则定时器不会启动。
  3. scheduledTimerWithTimeInterval这两个方法不需要手动调用fair,会自动执行,并且自动加入主循环池。
  4. init方法需要手动加入循环池,它会在设定的启动时间启动。
//加入主循环池中
[[NSRunLoop mainRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
//开始循环
[timer fire];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原文: objective-c常用方法列表(总结)在简书保存一份 第1章Objective-C学习环境准备1.1O...
    14cat阅读 1,193评论 0 2
  • 二、数学运算(math)函数2.1算术运算函数2.1.1rand()函数:产生随机数2.1.2abs()函数/la...
    问题饿阅读 3,548评论 1 11
  • 我一直那种很矫情的人,用我们东北话来说叫“隔路” 这种矫情从小就显现出来了,小学的时候发新书对每个小朋友来说都是一...
    湘北以楠阅读 480评论 0 0
  • 我在天津过人行横道时,差一点被车撞到,原因是我看到了马路对面的绿灯亮了,就准备过去了。但是后来我发现,对面的红绿灯...
    德川亮阅读 332评论 0 6
  • 今天阅读得到专栏何帆的北大读书俱乐部,看到这总结就截图来保存。发现到一件事情就是我目前的情况,就是过去我累积无数选...
    刘连忘烦阅读 113评论 0 0