#import <Foundation/Foundation.h>
@interface Point : NSObject
@property (nonatomic, assign) int x;
@property (nonatomic, assign) int y;
@end
@implementation Point
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// Objective-C offers several formatting options for various data types.
// Here are some examples of common string formatting tasks.
Point *p = [[Point alloc] init];
p.x = 1;
p.y = 2;
// For basic object description, use %@
NSLog(@"struct1: %@", p);
// To print the type of a value, use %@
NSLog(@"type: %@", NSStringFromClass([p class]));
// Formatting booleans
NSLog(@"bool: %d", YES);
// There are many options for formatting integers.
// Use %d for standard, base-10 formatting.
NSLog(@"int: %d", 123);
// This prints a binary representation.
NSLog(@"bin: %b", 14);
// This prints the character corresponding to the given integer.
NSLog(@"char: %c", 33);
// %x provides hex encoding.
NSLog(@"hex: %x", 456);
// There are also several formatting options for floats.
// For basic decimal formatting use %f.
NSLog(@"float1: %f", 78.9);
// %e and %E format the float in (slightly different versions of) scientific notation.
NSLog(@"float2: %e", 123400000.0);
NSLog(@"float3: %E", 123400000.0);
// For basic string printing use %@.
NSLog(@"str1: %@", @"\"string\"");
// To print a representation of a pointer, use %p.
NSLog(@"pointer: %p", p);
// When formatting numbers you will often want to control the width and precision of the resulting figure.
// To specify the width of an integer, use a number after the % in the verb.
// By default the result will be right-justified and padded with spaces.
NSLog(@"width1: |%6d|%6d|", 12, 345);
// You can also specify the width of printed floats,
// though usually you'll also want to restrict the decimal precision at the same time with the width.precision syntax.
NSLog(@"width2: |%6.2f|%6.2f|", 1.2, 3.45);
// To left-justify, use the - flag.
NSLog(@"width3: |%-6.2f|%-6.2f|", 1.2, 3.45);
// You may also want to control width when formatting strings,
// especially to ensure that they align in table-like output.
// For basic right-justified width.
NSLog(@"width4: |%6s|%6s|", "foo", "b");
// To left-justify use the - flag as with numbers.
NSLog(@"width5: |%-6s|%-6s|", "foo", "b");
// So far we've seen NSLog, which prints the formatted string to the console.
// NSString's stringWithFormat: formats and returns a string without printing it anywhere.
NSString *s = [NSString stringWithFormat:@"stringWithFormat: a %@", @"string"];
NSLog(@"%@", s);
// You can format+print to NSFileHandle other than stdout using writeData:.
NSFileHandle *stderr = [NSFileHandle fileHandleWithStandardError];
NSString *errorString = [NSString stringWithFormat:@"io: an %@\n", @"error"];
[stderr writeData:[errorString dataUsingEncoding:NSUTF8StringEncoding]];
}
return 0;
}