iOS常识



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 plain copy
  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 plain copy
  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。


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值