Shortcut to generate an NSRange for entire length of NSString?

IosObjective CNsstringNsrange

Ios Problem Overview


Is there a short way to say "entire string" rather than typing out:

NSMakeRange(0, myString.length)]

It seems silly that the longest part of this kind of code is the least important (because I usually want to search/replace within entire string)…

[myString replaceOccurrencesOfString:@"replace_me"
                          withString:replacementString
                             options:NSCaseInsensitiveSearch
                               range:NSMakeRange(0, myString.length)];

Ios Solutions


Solution 1 - Ios

Function? Category method?

- (NSRange)fullRange
{
    return (NSRange){0, [self length]};
}

[myString replaceOccurrencesOfString:@"replace_me"
                          withString:replacementString
                             options:NSCaseInsensitiveSearch
                               range:[myString fullRange]];

Solution 2 - Ios

Swift 4+, useful for NSRegularExpression and NSAttributedString

extension String {
    var nsRange : NSRange {
        return NSRange(self.startIndex..., in: self)
    }

    func range(from nsRange: NSRange) -> Range<String.Index>? {
        return Range(nsRange, in: self)
    }
}

Solution 3 - Ios

Not that I know of. But you could easily add an NSString category:

@interface NSString (MyRangeExtensions)
- (NSRange)fullRange
@end

@implementation NSString (MyRangeExtensions)
- (NSRange)fullRange {
  return (NSRange){0, self.length};
}

Solution 4 - Ios

Swift

NSMakeRange(0, str.length)

or as an extension:

extension NSString {
    func fullrange() -> NSRange {
        return NSMakeRange(0, self.length)
    }
}

Solution 5 - Ios

Swift 2:

extension String {
    var fullRange:Range<String.Index> { return startIndex..<endIndex }
}

as in

let swiftRange = "abc".fullRange

or

let nsRange = "abc".fullRange.toRange

Solution 6 - Ios

This is not shorter, but... Oh well

NSRange range = [str rangeOfString:str];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBasil BourqueView Question on Stackoverflow
Solution 1 - IosjscsView Answer on Stackoverflow
Solution 2 - IosvadianView Answer on Stackoverflow
Solution 3 - IosBJ HomerView Answer on Stackoverflow
Solution 4 - IosSwiftArchitectView Answer on Stackoverflow
Solution 5 - IosChris ConoverView Answer on Stackoverflow
Solution 6 - IosOdrakirView Answer on Stackoverflow