您的位置:首页 > 移动开发 > IOS开发

IOS:定义自己的Log函数

2013-07-03 18:10 274 查看
本文主要是为了表示怎么实现自己的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");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: