ios - 使用私有(private)方法使代码尽可能模块化

标签 ios objective-c uitableview ios6

在我的 -(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;

我的方法实现看起来有点乱,我想知道什么是正确的方法。我应该将此代码保留在原处,还是应该为日期格式创建另一个私有(private)方法?

假设我想创建私有(private)方法。像这样的东西:

   -(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 方法中写什么?

我对私有(private)方法的论点是 [self.videos objectAtIndex:indexPath.row] 但我不知道如何调用此方法以及在哪个实例变量上调用?

我需要在我的 View 类中创建一个 NSString 实例变量,或者我可以在 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 方法并在其上执行我的私有(private)方法?

最佳答案

一般的经验法则是,如果您打算重用逻辑,则将其放入可重用对象中。这个想法是为了防止重复。在你的情况下,你如何创建一个 DateUtils 类并将你的逻辑放在那里。创建类别是另一种选择。

示例用法:

NSString *youtubeVideoDateStr = [DateUtils formatDateWithString:@"..."];

关于ios - 使用私有(private)方法使代码尽可能模块化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14838907/

相关文章:

iPhone SDK : Inserting and updating a UITableView with a new row

c# - 适用于 iphone 应用程序的 MonoTouch & C# VS Objective C

iphone - 手势识别器未激活 - UIScrollView 内的 UIImageView

ios - 自定义 UITableViewCell 高度在移动时发生变化

ios - 为什么 Xcode 模拟器 View 与 View 层次结构 View 不同

iphone - 如何在使用SDWebimage显示之前先下载Cache中的网页图片?

ios - 设置导航栏图标的大小 ios

ios - PromiseKit.framework : bundle format unrecognized, 无效或不合适

ios - 创建UICollectionView的最大单元数

ios - UITableViewController 背景颜色设置为默认(白色),但显示为黑色