为什么 NSString 变空(没有原因)?
我对 Objective C 很着迷。请看下面的代码。
FirstViewController.h:
@interface FirstViewController : UIViewController {
IBOutlet UITextView *textView;
IBOutlet UIBarButtonItem *button;
NSString* superString;
}
- (IBAction)buttonDown;
FirstViewController.m:
- (void)viewDidLoad {
[super viewDidLoad];
superString = [NSString stringWithFormat:"%@", @"A_super_string_file.txt"];
[self buttonDown];
}
- (IBAction)buttonDown {
NSError* err = nil;
NSString* text = [NSString stringWithContentsOfFile:superString encoding:NSUTF8StringEncoding error:&err];
[textView setText:text];
}
- 运行应用程序。 A_super_string_file.txt 成功显示在textView中。
- 按下按钮。应用程序崩溃是因为 superString 引用了与步骤 1 中相同的地址,但该地址上有另一个变量或没有任何变量。 superString 上的打印说明不显示任何内容或随机其他变量(甚至可能是不同类型)。
会发生什么?我是一名技能开发人员,但对这种情况一无所知。非常感谢您的帮助!
更新:可能,它在工作中隐藏了自动释放。但是什么时候释放内存呢?每次都在不同的时刻还是在某个特定的时刻?
I am going crazy with Objective C. Please look to the following code.
FirstViewController.h:
@interface FirstViewController : UIViewController {
IBOutlet UITextView *textView;
IBOutlet UIBarButtonItem *button;
NSString* superString;
}
- (IBAction)buttonDown;
FirstViewController.m:
- (void)viewDidLoad {
[super viewDidLoad];
superString = [NSString stringWithFormat:"%@", @"A_super_string_file.txt"];
[self buttonDown];
}
- (IBAction)buttonDown {
NSError* err = nil;
NSString* text = [NSString stringWithContentsOfFile:superString encoding:NSUTF8StringEncoding error:&err];
[textView setText:text];
}
- Run the application. A_super_string_file.txt successfully displayed in textView.
- Press the button. The application crashes because superString refers on the same address as in the step 1 but there is another variable or nothing on this address. Print Description on superString displays nothing or random other variable (may be even different type).
What happens? I am a skill developer but have no idea in this case. Thanks a lot for help!
UPDATE: Possibly, it's hidden autorelease in the work. But when it releases memory? On different moment every time or on some exact moment?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSString
的 +stringWithFormat
: 是自动释放的。如果您希望它保留下来,您需要保留它。属性是实现此目的的好方法,因为它减少了您需要担心的内存管理量。
.h.m
NSString
's +stringWithFormat
: is autoreleasing. You need to retain it if you want it to stay around.Properties are a good way to do this, because it cuts down how much memory management you need to worry about yourself.
.h
.m
您需要保留 superString。
创建后立即。
然后在dealloc中释放它。
You need to retain superString.
immediately after creating it.
and then release it in dealloc.