IOS:定义自己的Log函数

来源:互联网 发布:mac安装aptget 编辑:程序博客网 时间:2024/05/18 15:25

本文主要是为了表示怎么实现自己的Log方法,方便在Release版本删除log信息。

代码主要来自:

iOS Recipes: Tips and Tricks for Awesome iPhone and iPad Apps

1.  PRPDebug.m
////  PRPDebug.m////  Created by andy on 7/3/13.////#import "PRPDebug.h"void PRPDebug(const char *fileName, int lineNumber, NSString *fmt, ...){    va_list args;    va_start(args, fmt);    static NSDateFormatter *debugFormatter = nil;    if (debugFormatter == nil) {        debugFormatter = [[NSDateFormatter alloc] init];        [debugFormatter setDateFormat:@"yyyyMMdd.HH:mm:ss"];    }    NSString *msg = [[NSString alloc] initWithFormat:fmt arguments:args];    NSString        *filePath = [[NSString alloc] initWithUTF8String:fileName];    NSString        *timestamp = [debugFormatter stringFromDate:[NSDate date]];    NSDictionary    *info = [[NSBundle mainBundle] infoDictionary];    NSString        *appName = [info objectForKey:(NSString *)kCFBundleNameKey];    fprintf(stdout, "%s %s[%s:%d] %s\n", [timestamp UTF8String], [appName UTF8String], [[filePath lastPathComponent] UTF8String], lineNumber, [msg UTF8String]);    va_end(args);    [msg release];    [filePath release];}

2. PRPDebug.h

////  PRPDebug.h////  Created by andy on 7/3/13.////#ifdef PRPDEBUG#define DLog(format...) PRPDebug(__FILE__,__LINE__,format)#else#define DLog(format...)#endif#import <Foundation/Foundation.h>void PRPDebug(const char *fileName, int lineNumber, NSString *fmt, ...);

3. 在Debug配置中增加PRPDEBUG 选项

Project Navigator选择项目,Build Settings中搜索 Other C Flags,在Debug 部分增加 -DPRPDEBUG 选项。



4. 包含头文件

#ifdef __OBJC__#import <Foundation/Foundation.h>#import <UIKit/UIKit.h>#import "PRPDebug.h" #endif
5. 调用方法
DLog(@"Hello");
原创粉丝点击