Read Objective-C messages, Foundation objects and collection examples.

Before starting: Basic C syntax and familiarity with objects.

Practice project: Extend the examples into a small Objective-C study demo. Explain the setup, one normal case and one failure or boundary case.

Start here: concepts and guided practice

  1. Objective-C: send an object a message

    Objective-C extends C with objects and message syntax. Foundation supplies NSString. The bracket expression asks the string for its length; Foundation is a framework, not the language itself.

    macOS with Xcode command-line tools and Foundation; save as study.m, compile clang -fobjc-arc -framework Foundation study.m -o study, then run ./study.

    #import <Foundation/Foundation.h>
    int main(void) {
        @autoreleasepool {
            NSString *name = @"Asha";
            NSLog(@"%lu", (unsigned long)[name length]);
        }
        return 0;
    }
    Check the output
    The log message contains 4; NSLog also adds diagnostic metadata.

    Replace Asha with Ben; expect 3. NSString length counts UTF-16 units, not always visible characters.

  2. Objective-C: loop over an array

    An NSArray stores objects. Number literals with @ create NSNumber objects. Fast enumeration visits each object without requiring an index.

    macOS with Xcode command-line tools and Foundation; save as study.m, compile clang -fobjc-arc -framework Foundation study.m -o study, then run ./study.

    #import <Foundation/Foundation.h>
    int main(void) {
        @autoreleasepool {
            NSArray *scores = @[@4, @7, @2];
            NSInteger total = 0;
            for (NSNumber *score in scores) {
                total += [score integerValue];
            }
            NSLog(@"%ld", (long)total);
        }
        return 0;
    }
    Check the output
    The log message contains 13.

    Try @[]; explain why total remains zero.

  3. Objective-C: check an optional object

    An object reference can be nil. Check for absence when the task requires a real object. Do not confuse nil with an empty but existing string.

    macOS with Xcode command-line tools and Foundation; save as study.m, compile clang -fobjc-arc -framework Foundation study.m -o study, then run ./study.

    #import <Foundation/Foundation.h>
    int main(void) {
        @autoreleasepool {
            NSString *name = nil;
            if (name == nil) {
                NSLog(@"Missing name");
            } else {
                NSLog(@"%@", name);
            }
        }
        return 0;
    }
    Check the output
    The log message contains Missing name.

    Try @"" and explain why it takes the else branch.

Open the Objective-C learning path on DevStudyHub · Play coding games on this blog

logoblog

No comments:

Post a Comment

Please do not enter any spam link in the comment box.