将 NSString 转换为 NSIndexPath
Posted
技术标签:
【中文标题】将 NSString 转换为 NSIndexPath【英文标题】:Convert NSString to NSIndexPath 【发布时间】:2013-12-27 21:45:49 【问题描述】:基本上我想做的是。当我使用 S3 获取对象时,我需要使用 requestTag 属性,该属性采用 NSString。我使用这个标签来确定哪个对象已经完成下载,从而确定哪个活动指示器停止旋转。下面是部分代码。如何将 NSString requestTag 转换为 NSIndexPath?
- (void)tableView:(UITableView *) tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIActivityIndicatorView *activityView = (UIActivityIndicatorView *)[cell viewWithTag:103];
if (![self.activityIndictatorOn containsObject:indexPath])
[self.activityIndictatorOn addObject:indexPath];
[activityView startAnimating];
...
getObjectRequest.requestTag = [NSString stringWithFormat:@"%@", indexPath];
-(void)request:(AmazonServiceRequest *)request didCompleteWithResponse:(AmazonServiceResponse *)response
NSLog(@"DOWNLOAD COMPLETE");
[self stopActivityIndicator:request.requestTag];
[self.downloadFinished addObject:request.requestTag];
-(void)stopActivityIndicator:(NSString *)rowAtIndexPath
//Need to convert rowAtIndexPath to NSIndexPath
//Following line results in warning
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:rowAtIndexPath];
UIActivityIndicatorView *activityView = (UIActivityIndicatorView *)[cell viewWithTag:103];
[activityView stopAnimating];
【问题讨论】:
【参考方案1】:[NSString stringWithFormat:@"%@", indexPath]
使用description
方法将索引路径转换为字符串
形式
length = 2, path = <section> - <row>
这有点难以解析回索引路径。
因此我建议将索引路径转换为请求字符串
格式为section:row
与
NSString *requestTag = [NSString stringWithFormat:@"%ld:%ld", (long)indexPath.section, (long)indexPath.row];
然后您可以轻松地将其转换回来
NSArray *tmp = [requestTag componentsSeparatedByString:@":"];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[tmp[1] integerValue] inSection:[tmp[0] integerValue]];
【讨论】:
【参考方案2】:好吧,您可以将indexPath
转换为NSString
并设置为requestTag
,如下所示:
getObjectRequest.requestTag = [NSString stringWithFormat:@"%ld,%ld", indexPath.section, indexPath.row];
然后将其转换回NSIndexPath
,如下所示:
NSArray *rowIndexArray = [rowAtIndexPath componentsSeparatedByString:@","];
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:rowIndexArray[1] inSection:rowIndexArray[0]];
【讨论】:
以上是关于将 NSString 转换为 NSIndexPath的主要内容,如果未能解决你的问题,请参考以下文章
将 'NSString *' 转换为 'CTStringRef *' 的不兼容类型
如果将一个NSObject从NSDictionary转换为NSString?