0

1 つのクラスの 1 つのプロパティに問題があります。違いがある場合は、iOS 6.1 でコーディングしています。

クラスはUIViewController次のようにヘッダー ファイルで宣言され、プロパティは次のようになります。

// Keeps track of time in seconds
@property (nonatomic, strong) NSNumber *timeInSeconds;

私の実装ファイルでは、次の 3 つの場合にプロパティを使用します。

  • 1つは、メソッドで時間を追加することです- (void)addTime

  • 1つは、メソッドで時間を減算することです- (void)subtractTime

これら 2 つのメソッドは、次のようにプロパティを使用します。

- (void)addTime
{
    CGFloat timeFloat = [self.timeInSeconds floatValue];

    // Here I set the value of the property timeInSeconds, but I can't access that value later on in the code!

    self.timeInSeconds = [NSNumber numberWithFloat:timeFloat +5];
    NSLog(@"Total Time:%@", self.timeInSeconds);
}

2 つのメソッドaddTimeとは本来の機能を実行し、足し算、引き算、足し算のようにsubtractTime、プロパティ値を適切に追跡します...timeInSeconds

問題は、同じ実装ファイルで次の 3 番目のメソッドを呼び出すときです。

- (void)updateLabelTime
{
   self.label.attributedText = [[NSAttributedString alloc]initWithString:[self.timeInSeconds stringValue]];


   [self.label setNeedsDisplay];

   [NSTimer scheduledTimerWithTimeInterval:0.8 target:self selector:@selector(updateLabelTime) userInfo:nil repeats:YES];
}

の代わりにNSAttributedStringwithを作成しようとしましたが、以前にandを使用して設定したプロパティの値を返す代わりに、 getter を呼び出して の新しいインスタンスを作成するという問題が解決しません。 .stringWithFormatinitWithStringtimeInSecondsaddTimesubtractTimetimeInSeconds

プロパティのゲッター/セッターを記述しないようにしましたが (iOS 6.1 を使用しているため)、違いはありません。

ラベルをランダムな文字列に設定するだけでうまくいきます。問題は、 の値timeInSecondsが 55 であることがわかっている場合でも、新しい が作成されること_timeInSecondsです。

私はフランス人なので、英語で最善を尽くしました。質問が初心者の iOS 開発者によって既に尋ねられている場合は、答えないでください。リダイレクトしてください。私は答えを見つけることができませんでした、ありがとう!

編集:これがカスタムゲッターです

- (float)timeInSeconds
{
if (!_timeInSeconds) {
    _timeInSeconds = 0;
}

return _timeInSeconds;
}

2番目の編集:

私が犯した初歩的な愚かな間違いは、addTime とsubtractTime が実際にプロトコルを実装していて、それらが別のクラスに「存在する」プロパティを設定していたため、アクセスできなかったことです。プロトコルを必要とする他のクラスは、addTime とsubtractTime が記述されているクラスの新しいインスタンスを作成していました。

行う必要があるのは、コントローラーをプロトコルのデリゲートとして設定することです。私は次のような方法でviewDidLoadメソッドでこれを行いました:

self.view.delegate = self;

すべての助けをありがとう。

4

2 に答える 2

1

ヘッダー ファイルで、次のプロパティを宣言します。

@property (assign) float timeInSeconds;

実装ファイル内:

@synthesize timeInSeconds = _timeInSeconds;

- (void)viewDidLoad
{
    [super viewDidLoad];
    _timeInSeconds = 0.0f;
}

- (void)addTime
{
    _timeInSeconds += 5.0f;
}

これはtimeInSeconds0 に初期化され、 を呼び出すたびに値が 5 ずつ増加しますaddTime。ラベルでその値を使用するには:

- (void)updateLabelTime
{
   self.label.text = [NSString stringWithFormat:@"%f", _timeInSeconds];
}
于 2013-04-16T18:03:58.807 に答える
0

カスタム ゲッターでは、スカラー値をオブジェクト プロパティに割り当てています。実際、オブジェクト プロパティに 0 を割り当てることは、オブジェクトを nil に設定することと同じです。

あなたがする必要があるのはこれです:

- (float)timeInSeconds
{
    if (!_timeInSeconds) {
        _timeInSeconds = [NSNumber numberWithFloat:0.0f];
        // or alternatively with the latest version of objective c
        // you can more simply use:
        // _timeInSeconds = @(0.0f);
    }

    return _timeInSeconds;
}
于 2013-04-16T19:17:34.377 に答える