ObjC-NsLog

在Objective-C中,NSLog相当于C语言中的printf,常用于文字输出。

NSLog (@"this is a test");
//控制台中就会输出this is a test

NSString *string=@"this is a test";
NSLog (@"string is :%@", string);
//控制台中就会输出this is a test

NSLog (@"x=%d, y=%d", 10, 20);
//控制台中就会输出x=10, y=20

BOOL start=YES;
NSLog(@"%@",start?@"YES":@"NO");
//控制台中就会输出YES

NSLog的占位符格式如下所示:

| 整型占位符 | |
| :————-: |:————-|:—–|
| %d,%i| 整数, %和d之间可以指定位数。如%02d:表示整数位数至少为2位。不足则补0 |
| %o | 八进制无符号整数, 没有 0 前缀 |
| %x | 十六进制无符号整数, 没有 0x 前缀 |
| %u | 十进制无符号整数 |
| 浮点占位符 | |
| %f | 以小数形式输出浮点数, 默认 6 位小数,如2.300000 |
| %e | 以指数形式(科学计数法)输出浮点数, 默认 6 位小数,如2.300000e+00 |
| 占位符附加字符 | |
| l |在整型和浮点型占位符之前, %d %o %x %u %f %e %g 代表长整型 和 长字符串|
| n(任意整数) | %8d 代表输出8位数字, 输出总位数 |
| .n | 浮点数 限制小数位数, %5.2f 表示 5位数字 2位小数, 字符串 截取字符个数 |
| – | 字符左对齐 |
| 字符占位符 | |
| %c | 单个字符输出,char * oct_c = "Octopus";|
| %s | 输出字符串,NSString *oct_oc = @"Octopus"; |
| 其它形式占位符 | |
| %p | 输出十六进制形式的指针地址,已0X为前缀,如0X00 |
| %@ | 输出 Object-C 对象 |

输出当前调用的方法名

NSLog(@"%s", __FUNCTION__);

输出应用程序目录的路径

NSLog(@"%@",NSHomeDirectory());

输出Point,Size,Rect等值

<CoreGraphics/CGGeometry.h>
CGPoint point = CGPointMake(0.0f, 0.0f);
CGSize size = CGSizeMake(10.0f, 10.0f);
CGRect rect = CGRectMake(point.x, point.y, size.width, size.height);

NSLog(@"point: %@", NSStringFromCGPoint(point));
NSLog(@"size: %@", NSStringFromCGSize(size));
NSLog(@"rect: %@", NSStringFromCGRect(rect));

<Foundation/NSGeometry.h>
NSPoint point = NSMakePoint(0.0f, 0.0f);
NSSize size = NSMakeSize(10.0f, 10.0f);
NSRect rect = NSMakeRect(point.x, point.y, size.width, size.height);
NSRange range = NSMakeRange(0, 10);
    
NSLog(@"point: %@", NSStringFromPoint(point));
NSLog(@"size: %@", NSStringFromSize(size));
NSLog(@"rect: %@", NSStringFromRect(rect));
NSLog(@"range: %@", NSStringFromRange(range));
NSLog(@"Class: %@", NSStringFromClass(self.class));

Dictionary

NSMutableDictionary *dict = [[ NSMutableDictionary alloc ] init ];
//add values
NSLog ( @"log dict =%@" , [dict description ]);

参数顺序

说明符携带n$,n表示顺序。看下面的例子

NSString *testName =  [NSString stringWithFormat: @"Employee %@ earned $%.2f this week.", @"John Doe", 1012.32];
NSLog(@"testName01=%@", testName);
    
testName = [NSString stringWithFormat: @"$%2$.2f was earned by employee %1$@.", @"John Doe", 1012.32];
NSLog(@"testName02=%@", testName);

输出如下
testName01=Employee John Doe earned $1012.32 this week.
testName02=$1012.32 was earned by employee John Doe.

参考资料

[Object – C 入门 之 数据类型详解]http://blog.csdn.net/shulianghan/article/details/38544659

[String Format Specifiers]https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html

    原文作者:马斯科特
    原文地址: https://www.jianshu.com/p/7be37f527ad3
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞