我正在尝试从 x 代码中的全局变量存储和加载一些文本。我在 main.m 中声明它,在 main 函数之外。然后当我想访问它时,我使用 extern。在我第二次单击包含文本的保存按钮后,应用程序崩溃。重写全局 labelString 字符串似乎会出现一些错误。你能解开这个谜题吗?
编辑:感谢 BKC,我对代码做了一些小改动,但是我仍然遇到同样的错误。代码已更新。
视图控制器.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (retain, nonatomic) IBOutlet UITextField *field;
- (IBAction)saveButton:(id)sender;
FOUNDATION_EXPORT NSString *labelString;
FOUNDATION_EXPORT NSString *separator;
@end
视图控制器.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize field;
NSString *labelString = @"";
NSString *separator = @"|<->|";
- (IBAction)saveButton:(id)sender {
if([field.text length] != 0) // if field isn't blank
{
if([labelString length] == 0) // nothing stored in labelString
{
labelString = field.text;
}
else // if something is already stored in labelString
{
NSString *str = [NSString stringWithFormat:@"%@%@%@", labelString, separator, field.text];
labelString = str;
}
field.text = @"";
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc {
[field release];
[super dealloc];
}
@end
谢谢你。