2013-10-18 45 views
0

我想從x代碼中存儲和加載全局變量的一些文本。我在主函數之外的main.m中聲明它。然後當我想訪問它時,我使用了extern。第二次點擊saveButton並顯示文本後,應用程序崩潰。看起來像重寫全局labelString字符串會有一些錯誤。你能解決這個難題嗎?xcode - 與字符串執行錯誤

編輯:由於BKC,我在代碼中做了一些小的修改,但是我仍然得到相同的錯誤。代碼已更新。

ViewController.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 

ViewController.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 

謝謝。

+1

請添加一個崩潰日誌。 – paulrehkugler

+0

在日誌中,唯一得到的是「(lldb)」但是我確實有一個當應用程序崩潰時立即出現的屏幕截圖。我不太清楚它是什麼意思,但:http://i.imgur.com/0jrqB5n.png – Sam

+0

@ user2874028在Xcode中添加一個異常斷點,這將使您的調試變得更加輕鬆:https://developer.apple.com/ library/ios/recipes/xcode_help-breakpoint_navigator/articles/adding_an_exception_breakpoint.html –

回答

0

您定義變量的方式並不正確。我使用任何全局變量在我的項目是這樣的..
聲明變量在.h文件中

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

定義在.m文件的varibale

NSString *labelString = @""; 

包含頭無論你想使用它。我認爲在你的代碼中它會因爲labelString變量的多次定義而崩潰。

+0

謝謝。在.m文件中,我應該如何定義它?在頂部或按鈕IBAction? – Sam

+0

你可以在頂部定義 – bhawesh

+0

它編譯但第二個按鈕點擊後它又崩潰了。我想不出做什麼。 – Sam