我们如何在 Objective-C 中打印不同类型的数据类型? [英] How can we print different types of data types in objective-C?

查看:69
本文介绍了我们如何在 Objective-C 中打印不同类型的数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打印所有类型的值,比如 char、long...等等,还有 nsdate、nsdictionary、frame ....我现在想打印每个类型变量的值.

I want to print values of all the types like char, long... so on and also nsdate, nsdictionary, frame ....I want to now to print values of each type variables.

推荐答案

原始类型,例如 int、float、double 等,可以使用 printf 以与在 C 中打印相同的方式打印、fprintf等.如果需要打印一个类的数据,通常可以使用NSObject的方法(NSString *)description得到一个表示对象数据的 NSString.这是一个例子...

Primitive types such as int, float, double, etc can be printed in the same fashion they are printed in C, using printf, fprintf, etc. If you need to print the data of a class you can often use NSObject's method (NSString *)description to get a NSString representing the data of the object. Here is an example...

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSString *string = [NSString stringWithFormat:@"Hello World!"];
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSArray *array = [NSArray arrayWithObject:@"Hello There!"];

    char *c_string = "Familiar ol' c string!";
    int number = 3;

    printf("C String: %s\n",c_string);
    printf("Int number: %u\n", number);
    //In 10.5+ do not use [NSString cString] as it has been deprecated
    printf("NSString: %s\n", [string UTF8String]);
    printf("NSDate: %s\n", [date.description UTF8String]);
    printf("NSArray: %s\n", [array.description UTF8String]);

    //If you are using this information for debugging, it's often useful to pass the object to NSLOG()

    NSLog(@"NSArray *array = \n%@", array);

    [pool drain];
    return 0;
}

我认为在运行示例时查看输出会有所帮助...

I thought it would helpful to see the output when the example is ran...

C String: Familiar ol' c string!
Int number: 3
NSString: Hello World!
NSDate: 2010-03-12 01:52:31 -0600
NSArray: (
    "Hello There!"
)
2010-03-12 01:52:31.385 printfTest[2828:a0f] NSArray *array = 
(
    "Hello There!"
)

这篇关于我们如何在 Objective-C 中打印不同类型的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆