【问题标题】:Objective-C Substring with range具有范围的 Objective-C 子字符串
【发布时间】:2015-04-19 13:56:14
【问题描述】:

我有一个指向 URL 的 NSString,如下所示:

https://.../uploads/video/video_file/115/spin_37.mp4

我想从 NSString(在本例中为 spin_37.mp4)获取 iOS 应用程序中的文件名

我正在尝试以下方法:

NSUInteger *startIndex = [self.videoURL rangeOfString:@"/" options:NSBackwardsSearch].location+1;
NSUInteger *endIndex = [self.videoURL length] - startIndex;

NSString *fileName = [self.videoURL substringWithRange:(startIndex, endIndex)];

但是我在使用 NSUInteger 时遇到了很多错误,即现在

Invalid operands to binary expression ('unsigned long' and 'NSUInteger *' (aka 'unsigned long *'))

谁能解释我做错了什么?

【问题讨论】:

  • 你认为这表明了什么:NSUInteger *startIndex???

标签: ios objective-c substring nsuinteger


【解决方案1】:

你总是可以只使用NSString's lastPathComponent API,它会接受一个带有“https://.../uploads/video/video_file/115/spin_37.mp4”的NSString并返回“spin_37.mp4”给你。

【讨论】:

  • 这正是我所需要的——谢谢!如果可以的话,我会在 10 分钟内接受答案。
【解决方案2】:

Michael 已经为您提供了实现您想做的事情的好方法。但是,至于您的问题,您做错了一些事情,这使您无法编译您编写的代码。首先,您声明了指向 NSUInteger 对象的错误指针; NSRange.location(第一行)和-length(第二行)都不返回一个指针,所以你的前两行应该声明常规的NSUIntegers。其次,您的第二行应该计算子字符串的长度,而不是结束索引(因为这是 NSRange 所要求的。最后,您的最后一行尝试传递两个整数值而不是 NSRange,即-substringWithRange: 方法接受什么作为参数。因此,要编译,您的代码应为:

NSUInteger startIndex = [self.videoURL rangeOfString:@"/" 
    options:NSBackwardsSearch].location+1;
NSUInteger length = [self.videoURL length] - startIndex - 1;

NSString *fileName = [self.videoURL substringWithRange:NSMakeRange(startIndex, length)];

但是,使用 Michael 已经建议的 NSString-lastPathComponent 方法可能会为问题提供更清晰的解决方案,因为在这种情况下,您似乎不需要 NSRanges 提供的更细粒度的控制.

【讨论】:

    【解决方案3】:

    你应该使用 NSString 的lastPathComponent 方法:

    NSString *pathString = @"https://.../uploads/video/video_file/115/spin_37.mp4";
    NSString *fileName = [pathString lastPathComponent];
    NSLog(@"fileName: %@", fileName);
    

    控制台输出:

    2015-04-19 17:04:25.992 MapTest[43165:952142] fileName: spin_37.mp4
    (lldb)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-04
      • 1970-01-01
      相关资源
      最近更新 更多