如何避免应用崩溃

来源:互联网 发布:手机壁纸软件may 编辑:程序博客网 时间:2024/05/20 05:04

How Not to Crash

来至:http://weekly.ios-wiki.com/issues/67

In 2015 I ran a series of posts on not writing crashing bugs (in iOS and Mac apps).

How Not to Crash #1: KVO and Manual Bindings

How Not to Crash #2: Mutation Exceptions

How Not to Crash #3: NSNotification

How Not to Crash #4: Threading

How Not to Crash #5: Threading, part 2

How Not to Crash #6: Properties and Accessors

How Not to Crash #7: Dealing with Nothing

How Not to Crash #8: Infrastructure

How Not to Crash #9: Mindset

http://inessential.com/hownottocrash

部分内容整理


How Not to Crash #2: 可变容器


可变集合不应该是公共API的一部分

@property (nonatomic, readonly) NSArray *operations;

@property (nonatomic) NSMutableArray *mutableOperations;

- (NSArray *)operations {
return [self.mutableOperations copy];
}

加分:不要相信他们的谎言

@property (readonly, copy) NSArray *layoutManagers;

这样足够安全吗?

在调试器中我发现,这是一个NSMutableArray(__NSArrayM) - 而且它不是一个copy的。这是NSTextStorage的_layoutManagers实例变量,它被声明为一个NSMutableArray。

而在我的枚举区块一些代码,做了的事情,引发了layoutManagers可变,导致应用程序崩溃。

答案: 迭代 layoutManagers 副本以后 。 问题解决了。

总结:如果不是自己的类内部的集合,使用的时候copy一份。

How Not to Crash #3: NSNotification

init 的时候注册通知

dealloc 的时候解除通知

[[NSNotificationCenter defaultCenter] removeObserver:self];

为什么不是 viewdidload?

如果一个对象注册了一个通知,然后再注册一次,通知处理程序将被调用两次。没有自动合并。

(这曾经发生在过去对iOS很多viewDidLoad。人们会把注册码有-但记住的view可以unloadedreloaded,这意味着多个注册相同的通知。)

避免使用

[NSNotificationCenter addObserverForName:object:queue:usingBlock:]

But it’s a bad idea. You may have saved yourself writing a notification handler method, but you’ve made your housekeeping worse because now you have an extra object to keep around and do aremoveObserver: on later. That means no blanket unregistering; it means you’re back to doing audits; it means you have another thing to get right.


How Not to Crash #6: Properties and Accessors

- (void)someRandomMethod {
some stuff…
_thing = otherThing;
other stuff…
}

考虑到重写thing的set 方法 正确写法

- (void)someRandomMethod {
some stuff…
self.thing = otherThing;
other stuff…
}


Auto-synthesize

Don’t do->this

dealloc

没有必要在dealloc的设置属性为零。

除非是代理


Use weak

安全

How Not to Crash #7: 空对象


thing 为nil 的时候

[thing doStuff]; 不会crash

[self doSomething:thing]; 有可能崩溃

最为消息接受者不会崩溃

但作为参数有可能崩溃

我们可以使用断言

- (void)someMethod:(id)someParameter {
NSParameterAssert(someParameter);
…do whatever…
}


NSAssert(something == somethingElse, nil);



初始化变量。未初始化变量是喜欢玩汽油说没事 因为火柴在你口袋里。

0 0
原创粉丝点击