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