Chuyển đến nội dung

Bài 3 · Getting Started

Program Structure and NSLog

Learn how Objective-C programs are organized into header and implementation files, how #import works, and how to print values with NSLog and printf format codes.

A one-file program is fine for learning, but real Objective-C projects are split into many files. Each class gets a header (.h) that declares its public interface and an implementation file (.m) that holds the code. This lesson explains that structure, the difference between #import and #include, comments and naming conventions, and how to print values correctly with NSLog and printf.

Header and implementation files

A class named Greeter is normally written as two files.

Greeter.h declares what other code may use:

OBJECTIVEC
#import <Foundation/Foundation.h>

@interface Greeter : NSObject

- (void)sayHello;

@end

Greeter.m supplies the code:

OBJECTIVEC
#import "Greeter.h"

@implementation Greeter

- (void)sayHello {
    NSLog(@"Hello from Greeter");
}

@end

And main.m uses it:

OBJECTIVEC
#import "Greeter.h"

int main(void) {
    @autoreleasepool {
        Greeter *greeter = [[Greeter alloc] init];
        [greeter sayHello];
    }
    return 0;
}

You do not need to understand every symbol yet; Classes and Objects explains them. What matters here is the pattern: interface in the header, implementation in the .m file, and #import "Greeter.h" wherever the class is used.

Use angle brackets for system and framework headers (<Foundation/Foundation.h>) and quotes for your own project headers ("Greeter.h").

#import versus #include

In C, a header that is included twice can break the build, so C headers wrap their contents in "include guards". Objective-C adds #import, which includes a file at most once per compilation unit, with no guard needed. Use #import for Objective-C headers, and either one for C headers. Modern clang also supports @import Foundation;, which loads a precompiled module.

The next example shows what an include guard does. It is plain C, so it runs here: the "header" is pasted twice, and the guard stops the second copy from being compiled (otherwise the struct would be defined twice, which is an error).

C Stand-in (C): include guards

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Comments and naming

Comments work as in C: // line and /* block */. Documentation comments for Xcode begin with /// or /** ... */.

Naming conventions matter more than in most languages because Objective-C has no namespaces:

  • Classes start with a two or three letter prefix in UpperCamelCase: NSString, UIView, ABCGreeter. Choose your own prefix and keep it consistent.
  • Methods and variables use lowerCamelCase: sayHello, userName.
  • Methods read like phrases: [order addItem:book quantity:2].
  • Constants and enums carry the prefix too: ABCStatusActive.

Printing with NSLog

NSLog takes a format string like printf, but the string is an NSString (@"...") and it adds the %@ code for objects.

OBJECTIVEC
NSString *name = @"Ada";
NSInteger score = 42;
double ratio = 0.75;

NSLog(@"Player: %@", name);
NSLog(@"Score: %ld", (long)score);
NSLog(@"Ratio: %.2f", ratio);
NSLog(@"Initial: %c", 'A');

The table below lists the codes you will use most.

Code Type Example
%@ any Objective-C object NSLog(@"%@", name)
%d / %i int NSLog(@"%d", 7)
%ld long, NSInteger (cast to long) NSLog(@"%ld", (long)n)
%lu unsigned long, NSUInteger (cast) NSLog(@"%lu", (unsigned long)n)
%f, %.2f double NSLog(@"%.2f", 3.14159)
%c one character NSLog(@"%c", 'x')
%s C string (char *) NSLog(@"%s", "text")
%p pointer address NSLog(@"%p", obj)
%% a literal percent sign NSLog(@"100%%")

NSInteger and NSUInteger change size between 32-bit and 64-bit platforms. Cast them to long or unsigned long and use %ld and %lu so the code is correct everywhere. Using %d with an NSInteger is a classic bug.

NSLog versus printf

  • NSLog writes to standard error, adds a timestamp and process info, and is slower. It is good for debugging. In a Debug build it also shows up in the Xcode console.
  • printf writes plain text to standard output and is what you want for command-line tools that other programs read.
  • printf cannot print objects with %@. To print an NSString with it, convert: printf("%s\n", [name UTF8String]);.
  • Use fprintf(stderr, ...) when you want plain text on the error stream.

A common pattern is a macro that logs only in debug builds:

OBJECTIVEC
#ifdef DEBUG
  #define DLog(fmt, ...) NSLog((@"%s: " fmt), __PRETTY_FUNCTION__, ##__VA_ARGS__)
#else
  #define DLog(fmt, ...)
#endif

Stand-in: format codes in C

The C format codes behave the same as the ones above, including the cast rule for platform-sized integers. This stand-in uses long and size_t, the C equivalents of NSInteger and NSUInteger.

C Stand-in (C): format codes and casts

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: a debug-only logging macro

The DLog idea works the same way in C, so you can try it. Change #define DEBUG to a comment to see the output disappear.

C Stand-in (C): logging macro that compiles away

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which line imports one of your own project headers?

    Project headers use quotes; system and framework headers use angle brackets.
  2. 2. What is the main advantage of #import over #include?

    #import avoids duplicate inclusion without manual include guards.
  3. 3. How should you print an NSInteger named n on every platform?

    NSInteger is 32 or 64 bits depending on the platform, so cast to long and use %ld.
  4. 4. Which format code prints an NSString object?

    %@ calls the object's description. %s expects a C string.

Summary

  • A class is split into a .h header (interface) and a .m file (implementation).
  • Use #import "X.h" for your headers and #import <Framework/X.h> for system ones.
  • Objective-C has no namespaces, so class names carry a prefix.
  • NSLog supports %@ and writes a timestamped line to standard error; printf is plain C output.
  • Cast NSInteger and NSUInteger to long and unsigned long when formatting.

Next: Compiling with clang and GNUstep

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.