0

I've searched other questions and can't seem to find a similar problem. Either I am something completely wrong or I am blind. But here goes the code:

@autoreleasepool {

    NSMutableString *sense = [[NSMutableString alloc] init];
    NSMutableArray *senses = [[NSMutableArray alloc] init];

....... other code which initializes rL and count/length .......

    for (index=0;index<count;index++) {
        for (j=0;j<length;j++) {
            c = [rL characterAtIndex:j];
            switch (c) {
                case '.':
                    [senses addObject:sense];
                    [sense setString:@""];
                    break;
                default:
                    [sense appendFormat:@"%c",c];
                    break;
            }
        }
    }
}

When I do this, and iterate, in debug mode, I see that all objects in senses are same as whatever the last value of sense was.

what am I doing wrong?

0

2 Answers 2

1

"sense" is always the same object. It is a mutable string, so the contents can change, but it is always the same object. So senses will contain that single object, multiple times. You could instead use

[senses addObject:[sense copy]];
Sign up to request clarification or add additional context in comments.

1 Comment

I thought that was something I was missing. Thanks, that's exactly what I wanted.
1

The immediate solution could be to change:

[senses addObject:sense];

to:

[senses addObject:[NSString stringWithString:sense]];

This will add unique instances instead of adding the same mutable string over and over.

But it appears you are splitting a string up using the "." characters as a delimiter.

There's an easier way:

NSArray *senses = [rl componentsSeparatedByString:@"."];

That's it - one line.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.