Domanda

Sto seguendo attraverso uno dei primissimi esempi di Learning Objective-C su Mac . Il mio codice è quasi esattamente lo stesso del codice nel libro (un paio di spazi e parentesi banali possono essere diversi). Ecco come si presenta:

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

Quando eseguo il codice, questo è ciò che ottengo nella console:

[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

Non sono sicuro perché questo sta accadendo. So che ha qualcosa a che fare con la funzione boolString, perché quando io commento la chiamata a esso, il programma funziona bene. Il mio istinto mi dice che questo ha qualcosa a che fare con qualcosa di nuovo di gestione della memoria in Snow Leopard (questo libro precede Snow Leopard da circa sei mesi). Chiunque sa che cosa il problema potrebbe essere?

È stato utile?

Soluzione

Si dispone di un errore di battitura in linea 30. Si vuole% d, e non $ d. Perché vi state perdendo il secondo segnaposto decimale, si finisce per passare 42 al% @, e NSLog cerca di risolvere il riferimento posizione di memoria 42 come se fosse il puntatore ad una stringa, e si crash.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top