2

Obj-C で繰り返し宣言のコードを減らす方法はありますか?

例えば:

私は持っている

    localNotification.fireDate = self.dueDate;
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    localNotification.alertBody = self.text;
    localNotification.soundName = UILocalNotificationDefaultSoundName;

このようなものに単純化できますか?

 localNotification
    .fireDate = self.dueDate;
    .timeZone = [NSTimeZone defaultTimeZone];
    .alertBody = self.text;
    .soundName = UILocalNotificationDefaultSoundName;

ありがとう!

4

2 に答える 2

6

Key-Value-Coding を使用できます。最初に、プロパティ名をキーとして値をディクショナリにパックします

NSDictionary *parameters = @{@"fireDate": self.dueDate,
                                 @"timeZone":[NSTimeZone defaultTimeZone],
                                 @"alertBody":self.text,
                                 @"soundName": UILocalNotificationDefaultSoundName }

、ブロックを使用してキーとオブジェクトを簡単に列挙できるよりも。

[parameters enumerateKeysAndObjectsUsingBlock: ^(id key, 
                                                 id object, 
                                                 BOOL *stop) 
{
    [localNotification setValue:object forKey:key];
}];

このコードを何度も使用する場合は、辞書を取得して列挙を停止するメソッドを使用して、NSNotification にカテゴリを作成します。

単に使用できるよりも

[localNotification setValuesForKeysWithDictionary:parameters];

ドキュメント


もちろん、もっと短く書くこともできます:

[localNotification setValuesForKeysWithDictionary:@{@"fireDate": self.dueDate,
                                                    @"timeZone":[NSTimeZone defaultTimeZone],
                                                    @"alertBody":self.text,
                                                    @"soundName": UILocalNotificationDefaultSoundName }];

これで、提案された構文とほぼ同じくらいコンパクトになりました。

于 2013-09-05T21:27:50.320 に答える
2

唯一の方法は、設定したいパラメータを取るメソッドを宣言することです。

-(void)notification:(UILocalNotification *)notification setFireDate:(NSDate *)date
   setAlertBody:(NSString *)alertBody {

   notification.fireDate = date;
   notification.alertBody = alertBody;
   notification.timeZone = [NSTimeZone defaultTimeZone];
   notification.soundName = UILocalNotificationDefaultSoundName; 
}

次の 2 行は、「デフォルト」の設定と見なすことができます。これらの行を、必要なデフォルト値に変更します。それで...

UILocalNotification *myNotification = ...
NSDate *tenMinutesAway = [NSDate ... 
[self notification:myNotification setFireDate:tenMinutesAway setAlertBody:@"Hello world!"];

また、サブクラスUILocalNotification化を見て、-initメソッドでそこに一連のデフォルトの動作を設定することもできます。これにより、何度も入力する必要がなくなり.soundNameます.timeZone

于 2013-09-05T20:52:33.540 に答える