gpt4 book ai didi

objective-c - NSString 内存管理问题 : message sent to deallocated instance

转载 作者:行者123 更新时间:2023-12-01 14:01:17 25 4
gpt4 key购买 nike

我有一个 NSString 声明如下:

.h:

@interface ViewController : UIViewController

{

NSString * aString;

}
@property(nonatomic,copy)NSString *aString;

.m :

@synthesize aString;

......

aString=[[NSString alloc]init];
aString=@"Hello World";

NSLog(@"%@",aString);//The app crashes here

应用程序崩溃并显示此堆栈跟踪:

-[CFString respondsToSelector:]: message sent to deallocated instance

最佳答案

删除行:

aString=[[NSString alloc]init];

并为属性设置值:

self.aString=@"Hello World";

Doing: aString=@"Hello World"; 意味着您正在为实例变量设置值,而不使用属性的访问器方法,那么您负责内存管理,而且更多复杂的。通过以下方式获取值:self.aString also.
附言始终通过属性工作,几乎从不使用实例变量,(仅在 dealloc 方法中释放 ivar,否则如果您不擅长内存管理,您将始终遇到问题,但属性为您做了一切)

关于objective-c - NSString 内存管理问题 : message sent to deallocated instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11047353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com