簡(jiǎn)介
NSAssertionHandler,斷言。
NSAssertionHandler實(shí)例是自動(dòng)創(chuàng)建的,用于處理錯(cuò)誤斷言。斷言宏,比如NSAssert和NSCAssert,用于評(píng)估一個(gè)條件,如果條件評(píng)估為錯(cuò)誤,這個(gè)宏向NSAssertionHandler實(shí)例發(fā)送一個(gè)表示錯(cuò)誤的字符串。每個(gè)線程都有它自己的NSAssertionHandler實(shí)例。斷言處理程序調(diào)用的時(shí)候,會(huì)打印一條錯(cuò)誤信息,包含斷言的方法或類,并拋出一個(gè)NSInternalInconsistencyException。
注意:一般情況下我們精良不要使用這個(gè)類,他可能導(dǎo)致不能預(yù)測(cè)的錯(cuò)誤,尤其是在你的線上的版本中
方法
+ currentHandler//返回當(dāng)前線程的斷言處理實(shí)例。
如果當(dāng)前線程沒(méi)有相關(guān)聯(lián)的斷言處理實(shí)例,這個(gè)方法會(huì)創(chuàng)建一個(gè)并將它分配給這個(gè)線程。
- handleFailureInFunction:file:lineNumber:description:
記錄錯(cuò)誤信息日志(使用NSLog),包含函數(shù)名,文件名和行號(hào)。
- (void)handleFailureInFunction:(NSString *)functionName file:(NSString *)fileName lineNumber:(NSInteger)line description:(NSString *)format,...
參數(shù)
functionName:失敗的函數(shù)
fileName:失敗的源文件
line:失敗的行數(shù)
format,...:格式化字符串
拋出NSInternalInconsistencyException。
- (void)handleFailureInMethod:(SEL)selector object:(id)object file:(NSString *)fileName lineNumber:(NSInter)line description:(NSString *)format,...
參數(shù)
selector:失敗的方法的選擇器
object:失敗的對(duì)象
fileName:失敗的源文件
line:失敗的行數(shù)
format,...:格式化字符串
如果你需要自定義NSAssertionHandler的行為,創(chuàng)建子類,重寫handleFailureInMethod:object:file:lineNumber:description:和handleFailureInFunction:file:lineNumber:description:方法,然后將你的實(shí)例用這個(gè)鍵安裝到當(dāng)前的線程屬性字典。
@interface LoggingAssertionHandler : NSAssertionHandler
@end
@implementation LoggingAssertionHandler
- (void)handleFailureInMethod:(SEL)selector
object:(id)object
file:(NSString *)fileName
lineNumber:(NSInteger)line
description:(NSString *)format, ...
{
NSLog(@"NSAssert Failure: Method %@ for object %@ in %@#%i", NSStringFromSelector(selector), object, fileName, line);
}
- (void)handleFailureInFunction:(NSString *)functionName
file:(NSString *)fileName
lineNumber:(NSInteger)line
description:(NSString *)format, ...
{
NSLog(@"NSCAssert Failure: Function (%@) in %@#%i", functionName, fileName, line);
}
@end
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSAssertionHandler *assertionHandler = [[LoggingAssertionHandler alloc] init];
[[[NSThread currentThread] threadDictionary] setValue:assertionHandler
forKey:NSAssertionHandlerKey];
// ...
return YES;
}