Objective-c Iphone如何设置属性的默认值

时间:2009-04-28 13:47:55

标签: iphone objective-c properties constructor

您好我在ViewController.h中有以下代码:

#import <UIKit/UIKit.h>

@interface CalcViewController : UIViewController {
    NSNumber* result;
    NSString* input;
    //NSString* input = @"";

    IBOutlet UITextField* display;
}

@property (retain) NSNumber* result;
@property (retain) NSString* input;
@property (nonatomic, retain) UITextField* display;

@end

问题是我想在输入中附加一个字符串,但是当它仍然为空时这是不可能的。这就是为什么我想将输入的默认值设置为@“”。但是我在哪里放这个代码。

我知道一种可能的解决方案,你把它放在一个默认的构造函数中。但我不知道在哪个文件中放这个。我应该从哪里打电话。

不幸的是,我对C的了解有限,并且意识到也许.h文件不是正确的地方。

如果您需要,项目类型是基于视图的应用程序。

希望你能提供帮助。

4 个答案:

答案 0 :(得分:16)

您可能会发现阅读有关Objective-C或Cocoa的一些文档很有用。如果您在StackOverflow或Google上执行搜索,您可能会在阅读材料上找到一些很好的建议。

要回答你的问题,你应该有一个@implementation of CalcViewController。人们通常会将此@implementation放在* .m文件中。如果您的* .h文件名为“ViewController.h”,那么实现将进入“ViewController.m”。

然后,您将创建UIViewController的初始化函数的副本并将其放在那里(我不知道默认的init函数是什么)。

例如:

@implementation CalcViewController

@synthesize result;
@synthesize input;

- (id)initWithNibName:(NSString*)aNibName bundle:(NSBundle*)aBundle
{
    self = [super initWithNibName:aNibName bundle:aBundle]; // The UIViewController's version of init
    if (self) {
        input = [[NSString alloc] initWithString:@""]; // You should create a new string as you'll want to release this in your dealloc
    }
    return self;
}

- (void)dealloc
{
    [input release];
    [super dealloc];
}
@end // end of the @implementation of CalcViewController

注意:

  • 您可能希望将文件重命名为CalcViewController。我相信Xcode的重构引擎更容易处理。
  • 当您使用Interface Builder连接时,您不需要为显示实例变量声明@property。除非您希望CalcViewController的客户端经常更改它

编辑: 2009年4月28日:美国东部时间上午10:20:我建议实际分配一个NSString,因为你应该在dealloc中从技术上释放它。

编辑: 2009年4月28日:美国东部时间上午11:11:我更新了@implementation以使用UIViewController的init版本。

答案 1 :(得分:9)

非常好的问题。简短的回答是在init函数中初始化值。您需要覆盖默认的init函数,以便在使用对象之前准备好默认值。 我想建议人们不要建议其他人阅读文件;如果可以,请直接回答问题。

答案 2 :(得分:3)

另一种选择是为输入属性编写自己的getter,如果实例变量为nil则返回@“”。即使您意外或故意将nil分配给输入,这也会起作用,而使用init设置默认值会破坏。

答案 3 :(得分:0)

实现它的最明显的方法如下:

  1. 在viewcontroller.m文件中,覆盖默认的init方法。 每次初始化视图控制器时都会调用此方法。 因此,这是初始化变量的最佳方式。

    - (id)initWithNibName:(NSString*)aNibName bundle:(NSBundle*)aBundle {
        self = [super initWithNibName:aNibName bundle:aBundle]; // The UIViewController's     version of init
        if (self) {
            varName = [[NSString alloc] initWithString:@""];
        }
        return self;
    }
    
  2. 现在,在你的代码中,你想要在你的代码中添加一个字符串 原始字符串,只需使用:varName = [NSString stringwithformat:@"%@%@", varName, newString];