iOS小常识

来源:互联网 发布:中国2016年gdp数据 编辑:程序博客网 时间:2024/04/29 01:18

Objective-C和C语言一样,提供了一些标准宏,描述了当前文件,所在源码文件的行数,以及函数信息。而Objective-C本身,也提供了相关的类类型。都可以应用在调试和错误处理日志当中。

预处理器在C/C++/Objective-C语言中提供的宏

*   __func__%s 当前函数签名
*   __LINE__ %d 在源代码文件中当前所在行数

*   __FILE__ %s 当前源代码文件全路径

*   __PRETTY_FUNCTION__ %s 像 __func__,但是包含了C++代码中的隐形类型信息。


在Objective-C使用的一些日志信息

 *   NSStringFromSelector(_cmd) %@ 当前selector名称
 *   NSStringFromClass([self class]) %@ 当前对象名
 *   [[NSString stringWithUTF8String:**FILE**] lastPathComponent] %@ 源代码文件名
 *   [NSThread callStackSymbols] %@ 当前stack的可读字符串数组。仅在调度时使用。

**例子代码:**

[cpp] view plaincopy
  1. #import <foundation /Foundation.h>  
  2.   
  3. @interface TestObj : NSObject  
  4. - (void) fun:(NSString *)input;  
  5. @end  
  6.   
  7. @implementation TestObj  
  8. - (void) fun:(NSString *)input {  
  9.     NSLog(@"%s:%d:%s:%s", __func__, __LINE__, __FILE__,__PRETTY_FUNCTION__);  
  10.     NSLog(@"%@",NSStringFromSelector(_cmd));  
  11.     NSLog(@"%@",NSStringFromClass([self class]));  
  12.     NSLog(@"%@",[[NSString stringWithUTF8String:__FILE__] lastPathComponent]);  
  13.     NSLog(@"%@",[NSThread callStackSymbols]);  
  14.     NSLog(@"%@",input);}  
  15.  @end  
  16.   
  17. int main (int argc, const char * argv[]){  
  18.     @autoreleasepool {  
  19.         TestObj *to = [[TestObj alloc]init];  
  20.         [to fun:@"call"];         
  21.         [to release];      
  22.     }      
  23.     return 0;  
  24. }  


 更佳实践


在预处理文件(Prefix.pch)中添加一些宏。


[cpp] view plaincopy
  1. #define _LOG_DEBUG_ 1  
  2. #define _LOG_INFO_  0  
  3. #define _LOG_ERROR_ 0  
  4.   
  5. #if _LOG_ERROR_  
  6.     #define LogDebug(fmt, ...) ;  
  7.     #define LogInfo(fmt, ...) ;  
  8.     #define LogError(fmt, ...) NSLog((@"%s [ERROR] " fmt), __FUNCTION__, ##__VA_ARGS__)  
  9. #elif _LOG_INFO_  
  10.     #define LogDebug(fmt, ...) ;  
  11.     #define LogInfo(fmt, ...) NSLog((@"%s [INFO] " fmt), __FUNCTION__, ##__VA_ARGS__)  
  12.     #define LogError(fmt, ...) NSLog((@"%s [ERROR] " fmt), __FUNCTION__, ##__VA_ARGS__)  
  13. #elif _LOG_DEBUG_  
  14.     #define LogDebug(fmt, ...) NSLog((@"%s [DEBUG] " fmt), __FUNCTION__, ##__VA_ARGS__)  
  15.     #define LogInfo(fmt, ...) NSLog((@"%s [INFO] " fmt), __FUNCTION__, ##__VA_ARGS__)  
  16.     #define LogError(fmt, ...) NSLog((@"%s [ERROR] " fmt), __FUNCTION__, ##__VA_ARGS__)  
  17. #else  
  18.     #define LogDebug(fmt, ...) ;  
  19.     #define LogInfo(fmt, ...) ;  
  20.     #define LogError(fmt, ...) ;  
  21. #endif  

用LogDebug,LogInfo,LogError 来替代 NSlog。


(转自:http://blog.csdn.net/shiren1118/article/details/8674354)

原创粉丝点击