1

管理対象オブジェクト(このオブジェクトの他のプロパティに基づいて日付を計算する)にカスタム計算メソッドを追加したいと思います。

これを一時的な属性としてコーディングするのが良いのか、カテゴリ内のプロパティをこの管理対象オブジェクトに追加するのが良いのかわかりません。

どう思いますか?

これは私の現在のコード(カテゴリ)です:

.h:

@interface IBFinPeriod (DateCalculations)
@property (readonly) NSDate* periodBeginDate;
@end

.m:

#import "IBFinPeriod+DateCalculations.h"

@implementation IBFinPeriod (DateCalculations)

- (NSDate*)periodBeginDate
{
    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    if ([self.incPeriodTypeCode isEqualToString:@"M"]) {
        offsetComponents.month = - [self.incPeriodLength intValue];
    } else if ([self.incPeriodTypeCode isEqualToString:@"W"]) {
        offsetComponents.week = - [self.incPeriodLength intValue];
    }
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *beginDate = [calendar dateByAddingComponents:offsetComponents toDate:self.EndDate options:0];
    return beginDate;
}

@end
4

2 に答える 2

2

あなたの解決策はうまくいくようです。一時的なプロパティを使用した場合でも、その値を計算するためのコードが必要になるため、とにかくカテゴリが必要になります。

一時的なプロパティを持つことは、その値に頻繁にアクセスする場合に意味があります。その場合は、その値をキャッシュする必要があります。値に数回しかアクセスしない場合は、その必要はありません。

于 2012-07-05T20:01:59.620 に答える
1

カテゴリに提供されている読み取り専用プロパティは単純です-長い目で見れば。そして、そのオブジェクトモデルを汚しません。

ただし、派生プロパティは自動的に更新されるため、一時プロパティメソッドはユーザーにとって魅力的です。そしてそれは少し行くこのような何か...

@implementation IBFinPeriod (IBFinPeriod_Observations)


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

    if ([@"incPeriodTypeCode" isEqualToString: keyPath]  ) {
        [self updatePeriodBeginDate];
    }
    else {
        [super observeValueForKeyPath: keyPath ofObject:object change:change context:context];
    }
}


- (void)updatePeriodBeginDate
{
    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    if ([self.incPeriodTypeCode isEqualToString:@"M"]) {
        offsetComponents.month = - [self.incPeriodLength intValue];
    } else if ([self.incPeriodTypeCode isEqualToString:@"W"]) {
        offsetComponents.week = - [self.incPeriodLength intValue];
    }
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *beginDate = [calendar dateByAddingComponents:offsetComponents toDate:self.EndDate options:0];

    // NOW SET THE TRANSIENT PROPERTY HERE
    [self setPeriodBeginDate: beginDate];
//        return beginDate; // NOt returning anymore
}


@end
于 2013-06-20T00:14:47.097 に答える