0

私の-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法では、セルラベルのYouTubeビデオの日付を返すこのコードがあります:

   //Video upload date
   NSString *formattedString = [[[self.videos objectAtIndex:indexPath.row] objectForKey:@"uploaded"] stringByReplacingOccurrencesOfString:@"T" withString:@""];

   formattedString = [formattedString stringByReplacingCharactersInRange:NSMakeRange(18, 5) withString:@""];

   NSDateFormatter *df = [[NSDateFormatter alloc] init];

   [df setDateFormat:@"yyyy-MM-ddHH:mm:ss"];

   NSDate *date = [df dateFromString:formattedString];

   [df setDateFormat:@"dd/MM/yyyy"];

   NSString *dateStr = [df stringFromDate:date];

   cell.date.text = dateStr;

私のメソッドの実装は少し乱雑に見え、正しいアプローチは何か疑問に思っています。このコードをそのままにしておくべきですか、それとも日付の書式設定用に別のプライベート メソッドを作成する必要がありますか?

プライベートメソッドを作りたいとしましょう。何かのようなもの:

   -(NSString *)formatDateWithString:(NSString *) mystring {

      NSString *formattedString = [mystring stringByReplacingOccurrencesOfString:@"T" withString:@""];

      formattedString = [formattedString stringByReplacingCharactersInRange:NSMakeRange(18, 5) withString:@""];

      NSDateFormatter *df = [[NSDateFormatter alloc] init];

      [df setDateFormat:@"yyyy-MM-ddHH:mm:ss"];

      NSDate *date = [df dateFromString:formattedString];

      [df setDateFormat:@"dd/MM/yyyy"];

      NSString *dateStr = [df stringFromDate:date];

      return dateStr; 
      }

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPathメソッドに何を書くべきですか?

私のプライベート メソッドの引数は次のようになります[self.videos objectAtIndex:indexPath.row]が、このメソッドをどのように呼び出すか、どのインスタンス変数で呼び出すかを失いました。

ビュー クラスでインスタンス変数を作成する必要がありNSStringますか、それともメソッドで NSString インスタンスを開始し、その-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath上でプライベート メソッドを実行できますか?

4

2 に答える 2

2

一般的な経験則として、ロジックを再利用する場合は、再利用可能なオブジェクトに配置します。アイデアは、重複を防ぐことです。あなたの場合、DateUtilsクラスを作成してそこにロジックを配置するのはどうですか。カテゴリを作成することも別のオプションです。

使用例:

NSString *youtubeVideoDateStr = [DateUtils formatDateWithString:@"..."];
于 2013-02-12T18:13:02.190 に答える
1

この質問に対する「正しい」答えは実際にはありません。「乱雑に見える」ことは定量化できる問題ではないため、変更の正当性を測定する方法はありません。

コードの保守が容易になると主張できれば、コードをリファクタリングする時間を正当化できるかもしれません。単純化するよりも、その機能の学習に費やす時間が増えるでしょうか?

于 2013-02-12T18:12:51.260 に答える