Search code examples
stringrandomnsmutablestring

NSString problems


I have problems with a simple NSString on Mac OS X:

NSString *letters = @"abcdefghijklmnopqrstuvwxyz0123456789";
myString = [myString stringByAppendingFormat:@"%c", [letters characterAtIndex:3]];

When I try to access this string again, Xcode is returning EXC_BAD_ACCESS This error just occures, when I'm using the format @"%c" When I'm using @"%@", sometimes the same error, sometimes this string: control 0x10040a480 and sometimes this:

{(
    <CFRunLoopObserver 0x10015ac60 [0x7fff70731ee0]>{locked = No, valid = Yes, activities = 0x21, repeats = Yes, order = 0, callout = _ZL15FlushAllBuffersP19__CFRunLoopObservermPv (0x7fff88a147d4), context = <CFRunLoopObserver context 0x0>}
)}

The errors occur randomly even, if I don't change anything in the code and re-run it.

I try to get a random String by doing:

randomString = @"";
    NSString *letters = @"abcdefghijklmnopqrstuvwxyz0123456789";
    srand(time(NULL));
    for (int i=0; i<5; i++)
    {
        randomString = [randomString stringByAppendingFormat:@"%c", [letters characterAtIndex:(rand()%[letters length])]];
    }

randomString is declared in header.h I also tried using a NSMutableString but that didn't work too. Every time I try to access the string (or mutable string) via @"%@" I'm getting EXC_BAD_ACCESS

Any idea? Hope somebody can help me!

Greets, Julian


Solution

  • Your problem is that myString gets autoreleased before you access it.

    You need to change:

    myString = [myString stringByAppendingFormat:@"%c", [letters characterAtIndex:3]];
    

    to:

    myString = [[myString stringByAppendingFormat:@"%c", [letters characterAtIndex:3]] retain];
    

    Remember to run [myString release]; when you are done with it.