Nitish
Nitish

Reputation: 14113

NSMutableString stringWithString giving crash

ten.textValue = [[NSMutableString alloc]init];
ten.textValue = [NSMutableString stringWithString:textField.text]; 

I am getting crash at second line.
ten.textValue is NSMutableString.

Upvotes: 0

Views: 381

Answers (2)

Skybird
Skybird

Reputation: 159

When you create your ten.textValue = [[NSMutableString alloc]init]; you are creating an object that you own.

When you try to add a string to it in the next line, you are creating an autoreleased string. This is confusing the compiler, which is reporting "hang on - this is an allocated, owned object already".

Instead:

if(ten.textValue)
{
    ten.textValue = [NSMutableString stringWithString: textField.text]};
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

It is probably because the text property of UITextField is nil by default, and passing nil to [NSMutableString stringWithString:nil] causes a crash.

You need to make sure the text is not nil when you pass it to be copied, for example like this:

[NSMutableString stringWithString: textField.text ? textField.text : @""]

You should also eliminate the first line - it serves no purpose, because the allocated and assigned value gets overwritten immediately.

Upvotes: 2

Related Questions