1

我正在学习在 Mac 上学习 Objective-C中非常早期的示例之一。我的代码与书中的代码几乎完全相同(几个空格和小括号可能会有所不同)。它看起来像这样:

#import <Foundation/Foundation.h>

BOOL areIntsDifferent (int thing1, int thing2) {
    if (thing1 == thing2) {
        return NO;
    }
    else {
        return YES;
    }

}

NSString * boolString (BOOL yesNo) {
    if (yesNo == NO) {
        return (@"NO");
    }
    else {
        return (@"YES");
    }
}


int main (int argc, const char * argv[]) {
    BOOL areTheyDifferent;

    areTheyDifferent = areIntsDifferent(5, 5);
    NSLog(@"are %d and %d different? %@", 5, 5, boolString(areTheyDifferent));

    areTheyDifferent = areIntsDifferent(23, 42);
    NSLog(@"are %d and $d different? %@", 23, 42, boolString(areTheyDifferent));

    return 0;
}

当我运行代码时,这是我在控制台中得到的:

[Session started at 2009-12-19 01:41:37 -0500.]
GNU gdb 6.3.50-20050815 (Apple version gdb-1346) (Fri Sep 18 20:40:51 UTC 2009)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin".tty /dev/ttys001
Loading program into debugger…
Program loaded.
run
[Switching to process 3125]
Running…
2009-12-19 01:41:38.432 BOOL Party[3125:a0f] are 5 and 5 different? NO
Program received signal:  “EXC_BAD_ACCESS”.
sharedlibrary apply-load-rules all

我不确定为什么会这样。我确实知道它与boolString函数有关,因为当我注释掉对它的调用时,程序运行良好。我的直觉告诉我,这与 Snow Leopard 中一些新的内存管理内容有关(这本书比 Snow Leopard 早了大约六个月)。有谁知道可能是什么问题?

4

1 回答 1

8

你在第 30 行有一个错字。你想要 %d,而不是 $d。因为您缺少第二个小数占位符,所以您最终将 42 传递给 %@,并且 NSLog 尝试取消引用内存位置 42,就好像它是指向字符串的指针一样,并且您崩溃了。

于 2009-12-19T06:57:26.223 回答