2011-02-12 56 views
0

我正在使用NSMutableString並有一些困難。每當我嘗試訪問它時,應用程序都會退出,並且不會在NSLog中聲明任何錯誤。使用NSMutableString(初學者)

我設置字符串中的觀點做了load方法,使我的字符串就能相當保留其信息不是被重置,但我不相信我的知識上,這是正確的。任何幫助都會很棒。謝謝!

#import <UIKit/UIKit.h> 

@class rootViewController; 

@interface Numpad : UIViewController { 

    rootViewController *viewController; 

    UIButton *one; 
    UIButton *two; 
    UIButton *three; 

    NSInteger *loggedNumbers; 
    NSMutableString *numberString; 
} 

-(IBAction)buttonClicked:(id)sender; 


@property (nonatomic, retain)IBOutlet UIButton *one; 
@property (nonatomic, retain)IBOutlet UIButton *two; 
@property (nonatomic, retain)IBOutlet UIButton *three; 

@property (nonatomic, retain) rootViewController *viewController; 


@end 

與.m

#import "Numpad.h" 


@implementation Numpad 

@synthesize viewController, one, two, three, four, five, six, seven, eight, nine, zero; 

- (void)initString{ 

} 

- (IBAction)buttonClicked:(id)sender{ 


    int stringLength = [numberString length]; 

    //NSLog(@"Number String before Switch: %@", numberString); 

    switch (((UIButton*)sender).tag){ 

     case 1: 
      { 
       [numberString insertString: @"1" atIndex: stringLength]; 
      } 
     break; 

     case 2: 
      { 
       [numberString insertString: @"2" atIndex: stringLength]; 
      } 
      break; 

     case 3: 
      { 
       [numberString insertString: @"3" atIndex: stringLength]; 
      } 
      break; 

     default: 
     break; 
    } 


    double myDouble = [numberString doubleValue]; 
    int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5)); 

    NSLog(@"Number String: %@", numberString); 
    NSLog(@"After int applied: %i", myInt); 
} 




/* 
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. 
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { 
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { 
     // Custom initialization 
    } 
    return self; 
} 
*/ 


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. 
- (void)viewDidLoad { 
    numberString = [[NSMutableString stringWithString: @""]; 
    [super viewDidLoad]; 
} 
+0

有沒有你不只是鑄造`tag`到`double`理由嗎?你爲什麼使用一個字符串作爲中間人? – 2011-02-12 21:01:26

+0

原因是這是某種鍵盤的實現。按1 2 3和字符串(以及雙)爲123,其中一個鑄造的標籤將是3 – 2011-02-12 21:06:20

回答

2

的字符串,本身不保留,因爲你是通過方便的方法分配值numberString所以你應該自己保留。所以viewDidLoad應該看起來像這樣。

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. 
- (void)viewDidLoad { 
    numberString = [[[NSMutableString stringWithString: @""] retain]; 
    [super viewDidLoad]; 
} 

,或者你應該給它分配

numberString = [[NSMutableString alloc] initWithString: @""] retain]; 
1

你需要的時候你初始化它保留您的字符串。