Objective-C Substring with range

3.3k Views Asked by At

I have an NSString that points to a URL, something like this:

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

I want to get the filename in my iOS app from the NSString (in this example, spin_37.mp4)

I'm trying the following:

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

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

But I'm running into a lot of errors with NSUInteger, namely right now

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

Can someone explain what I'm doing wrong?

3

There are 3 best solutions below

1
Michael Dautermann On BEST ANSWER

You could always just use NSString's lastPathComponent API which would take a NSString with "https://.../uploads/video/video_file/115/spin_37.mp4" and return "spin_37.mp4" to you.

0
ninjaproger On

You should use lastPathComponent method of NSString:

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

Console output:

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

Michael has already given you a good method to achieve what you'd like to do. However, as to your question, there are a few things that you are doing wrong which are preventing you from being able to compile the code you've written. First of all, you are declaring incorrect pointers to NSUInteger objects; neither NSRange.location (first line) nor -length (second line) returns a pointer, so your first two lines should be declaring regular NSUIntegers. Second, your second line should be calculating the length of the substring, not the end index (as that is what an NSRange requires. Finally, your last line is attempting to pass two integer values instead of an NSRange, which is what the method -substringWithRange: accepts as an argument. To compile, your code should therefore read:

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

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

However, using NSString's -lastPathComponent method as Michael already suggested probably gives a cleaner solution to the problem as in this situation you don't seem to need the more fine-grained control that NSRanges give.