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的可读字符串数组。仅在调度时使用。
**例子代码:**
- #import <foundation /Foundation.h>
- @interface TestObj : NSObject
- - (void) fun:(NSString *)input;
- @end
- @implementation TestObj
- - (void) fun:(NSString *)input {
- NSLog(@"%s:%d:%s:%s", __func__, __LINE__, __FILE__,__PRETTY_FUNCTION__);
- NSLog(@"%@",NSStringFromSelector(_cmd));
- NSLog(@"%@",NSStringFromClass([self class]));
- NSLog(@"%@",[[NSString stringWithUTF8String:__FILE__] lastPathComponent]);
- NSLog(@"%@",[NSThread callStackSymbols]);
- NSLog(@"%@",input);}
- @end
- int main (int argc, const char * argv[]){
- @autoreleasepool {
- TestObj *to = [[TestObj alloc]init];
- [to fun:@"call"];
- [to release];
- }
- return 0;
- }
更佳实践
在预处理文件(Prefix.pch)中添加一些宏。
- #define _LOG_DEBUG_ 1
- #define _LOG_INFO_ 0
- #define _LOG_ERROR_ 0
- #if _LOG_ERROR_
- #define LogDebug(fmt, ...) ;
- #define LogInfo(fmt, ...) ;
- #define LogError(fmt, ...) NSLog((@"%s [ERROR] " fmt), __FUNCTION__, ##__VA_ARGS__)
- #elif _LOG_INFO_
- #define LogDebug(fmt, ...) ;
- #define LogInfo(fmt, ...) NSLog((@"%s [INFO] " fmt), __FUNCTION__, ##__VA_ARGS__)
- #define LogError(fmt, ...) NSLog((@"%s [ERROR] " fmt), __FUNCTION__, ##__VA_ARGS__)
- #elif _LOG_DEBUG_
- #define LogDebug(fmt, ...) NSLog((@"%s [DEBUG] " fmt), __FUNCTION__, ##__VA_ARGS__)
- #define LogInfo(fmt, ...) NSLog((@"%s [INFO] " fmt), __FUNCTION__, ##__VA_ARGS__)
- #define LogError(fmt, ...) NSLog((@"%s [ERROR] " fmt), __FUNCTION__, ##__VA_ARGS__)
- #else
- #define LogDebug(fmt, ...) ;
- #define LogInfo(fmt, ...) ;
- #define LogError(fmt, ...) ;
- #endif
用LogDebug,LogInfo,LogError 来替代 NSlog。
(转自:http://blog.csdn.net/shiren1118/article/details/8674354)