使用NSMutableString(初学者)

时间:2011-02-12 20:47:29

标签: iphone objective-c xcode

我正在使用NSMutableString并遇到一些困难。每当我尝试访问它时应用程序退出并且它不会说NSLog中有任何问题。

我在view do 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];
}

2 个答案:

答案 0 :(得分: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 :(得分:1)

初始化时需要保留字符串。