Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we print different types of data types in objective-C?

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.

like image 254
Madan Mohan Avatar asked Mar 12 '10 05:03

Madan Mohan


People also ask

How do I print something in Objective C?

In C Language (Command Line Tool) Works with Objective C, too: printf("Hello World"); In Objective C: NSLog(@"Hello, World!");

How do I print the data type of a variable or a value?

To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.

How do you print double values in Objective C?

We can print the double value using both %f and %lf format specifier because printf treats both float and double are same. So, we can use both %f and %lf to print a double value.


1 Answers

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;
}

Edit: 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!"
)
like image 69
Stephen Melvin Avatar answered Sep 24 '22 22:09

Stephen Melvin