NSMutableString stringWithString 导致崩溃

发布于 2024-12-27 05:51:44 字数 207 浏览 4 评论 0原文

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

我在第二行崩溃了。
ten.textValue 是 NSMutableString

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

太傻旳人生 2025-01-03 05:51:44

这可能是因为 UITextFieldtext 属性 默认为 nil,并将 nil 传递给 [NSMutableString stringWithString:nil] 导致崩溃。

当您传递要复制的 text 时,您需要确保它不是 nil,例如:

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

您还应该删除第一行 - 它没有任何作用,因为分配的值会立即被覆盖。

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.

别闹i 2025-01-03 05:51:44

当您创建 ten.textValue = [[NSMutableString alloc]init]; 时,您正在创建一个您拥有的对象。

当您尝试在下一行中向其中添加字符串时,您正在创建一个自动释放的字符串。这让编译器感到困惑,它报告“挂起 - 这已经是一个已分配的、拥有的对象”。

反而:

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

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]};
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文