簡介
NSAssertionHandler,斷言。
NSAssertionHandler實例是自動創(chuàng)建的,用于處理錯誤斷言。斷言宏,比如NSAssert和NSCAssert,用于評估一個條件,如果條件評估為錯誤,這個宏向NSAssertionHandler實例發(fā)送一個表示錯誤的字符串。每個線程都有它自己的NSAssertionHandler實例。斷言處理程序調(diào)用的時候,會打印一條錯誤信息,包含斷言的方法或類,并拋出一個NSInternalInconsistencyException。
注意:一般情況下我們精良不要使用這個類,他可能導(dǎo)致不能預(yù)測的錯誤,尤其是在你的線上的版本中
方法
+ currentHandler//返回當(dāng)前線程的斷言處理實例。
如果當(dāng)前線程沒有相關(guān)聯(lián)的斷言處理實例,這個方法會創(chuàng)建一個并將它分配給這個線程。
- handleFailureInFunction:file:lineNumber:description:
記錄錯誤信息日志(使用NSLog),包含函數(shù)名,文件名和行號。
- (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:失敗的對象
fileName:失敗的源文件
line:失敗的行數(shù)
format,...:格式化字符串
如果你需要自定義NSAssertionHandler的行為,創(chuàng)建子類,重寫handleFailureInMethod:object:file:lineNumber:description:和handleFailureInFunction:file:lineNumber:description:方法,然后將你的實例用這個鍵安裝到當(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;
}