0

我正在尝试从 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 

谢谢你。

4

1 回答 1

0

您定义变量的方式不是正确的方式。我在我的项目中使用任何全局变量,如下所示。
在 .h 文件中声明变量

FOUNDATION_EXPORT NSString *labelString; // Use extern if mixing with C++

在 .m 文件中定义变量

NSString *labelString = @"";

在要使用的任何地方包含标题。我认为在您的代码中,由于 labelString 变量的多次定义而崩溃。

于 2013-10-18T19:23:44.973 回答