【问题标题】:How do I set a nonzero initial value in iOS?如何在 iOS 中设置非零初始值?
【发布时间】:2012-09-28 02:00:20
【问题描述】:

我有一个在标题中提到的 ivar

@interface MyClass : UIView{
    int thistone;}
- (IBAction)toneButton:(UIButton *)sender;
@property int thistone;
@end

并且我已经在实现中综合了它:

@implementation MyClass
@synthesize thistone;
- (IBAction)toneButton:(UIButton *)sender {
if(thistone<4)
    {thistone=1000;}   // I hate this line.
    else{thistone=thistone+1; }  
}

我找不到(或在任何手册中找到)设置非零初始值的方法。我希望它从 1000 开始,每次按下按钮时增加 1。该代码完全符合我的意图,但我猜有一种更合适的方法可以节省我上面的 if/else 语句。非常感谢代码修复或指向在线文档中特定行的指针。

【问题讨论】:

标签: ios button synthesize


【解决方案1】:

每个对象都有一个在实例化时调用的init 方法的变体。实现这个方法来做这样的设置。 UIView 尤其具有initWithFrame:initWithCoder。最好覆盖所有并调用单独的方法来执行所需的设置。

例如:

- (void)commonSetup
{
    thisTone = 1000;
}


- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        [self commonSetup];
    }

    return self;
}


- (id)initWithCoder:(NSCoder *)coder
{
    if (self = [super initWithCoder:coder])
    {
        [self commonSetup];
    }

    return self;
}

【讨论】:

  • 哇。你怎么知道我还在玩 CGRect?它有效,我想我还有很多阅读要做。谢谢。实际上,比我的 if/else 更多的代码输入,但让我更深入地了解 Obj C 概念。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-01
  • 2023-01-30
  • 1970-01-01
  • 2017-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多