【iOS】导致crash的方法

1.数组,字典,集合等下标越界,或者insert了一个nil对象。

- (void)testArrayOutOfBounds
{
    NSArray *testArray = @[@1,@2,@3];
    
    NSNumber *num = testArray[3];
}
- (void)testDicSetNilValueCrash
{
    // 构造不可变字典时 key和value都不能为空
    NSString *nilValue = nil;
    NSString *nilKey = nil;
    NSDictionary *dic1 = @{@"key" : nilValue};
    NSDictionary *dic2 = @{nilKey : @"value"};
}
- (void)testMutableDicSetNilValueCrash
{
    NSString *value = nil;
    NSMutableDictionary *mDic = [NSMutableDictionary dictionary];
    
    // via Dic set, leading crash
    [mDic setObject:value forKey:@"key"];
    
    // via KVO set, it's safe
    [mDic setValue:value forKey:@"key"];
}

2.调用了一个不存在的方法,而没有实现消息转发

- (void)testUnrecogernizedSelectorCash
{
    [self performSelector:@selector(testSel) withObject:nil afterDelay:0];
}

3.多线程并发导致的。当某个对象会被多个线程修改的时候,有可能一个线程访问这个对象的时候另一个线程已经把它删掉了,导致crash。
解决方法:加锁或者用@synchronized

4.repeat的NSTimer
timer对target持有强引用, 必须确保dealloc前已经invalidate并设为nil, 否则会内存泄漏

5.强引用一个单例会崩溃

6.强引用delegate不知道会不会崩溃???

7.tableView

- (void)testTableViewUpdateCrash
{
    NSIndexPath *insertIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    NSIndexPath *deleteIndexPath = [NSIndexPath indexPathForRow:1 inSection:0];
    NSIndexPath *reloadIndexPath = [NSIndexPath indexPathForRow:2 inSection:0];
    NSIndexPath *moved1IndexPath = [NSIndexPath indexPathForRow:3 inSection:0];
    NSIndexPath *moved2IndexPath = [NSIndexPath indexPathForRow:4 inSection:0];

    [self.tableView beginUpdates];
    
    [self.tableView insertRowsAtIndexPaths:@[insertIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView deleteRowsAtIndexPaths:@[deleteIndexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView reloadRowsAtIndexPaths:@[reloadIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView moveRowAtIndexPath:moved1IndexPath toIndexPath:moved2IndexPath];
    
    [self.tableView endUpdates];
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,611评论 8 265
  • Baymax:网易iOS App运行时Crash自动防护实践 版权声明本文转自网易杭州前端技术部公众号,由作者授权...
    IOS开发攻城狮_Fyc阅读 6,815评论 2 34
  • OC语言基础 1.类与对象 类方法 OC的类方法只有2种:静态方法和实例方法两种 在OC中,只要方法声明在@int...
    奇异果好补阅读 4,348评论 0 11
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,142评论 1 32
  • 清明,仿佛必有点雨才能称为清明。 而别家,生于清明死于清明的都多。 而伴随别家孩子诞生的,就是淅淅沥沥的小雨,竟无...
    溪英阅读 227评论 0 0