Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortcut to generate an NSRange for entire length of NSString?

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)]; 
like image 606
Basil Bourque Avatar asked Feb 25 '13 08:02

Basil Bourque


2 Answers

Function? Category method?

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

[myString replaceOccurrencesOfString:@"replace_me"                           withString:replacementString                              options:NSCaseInsensitiveSearch                                range:[myString fullRange]]; 
like image 147
jscs Avatar answered Sep 22 '22 12:09

jscs


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)     } } 
like image 22
vadian Avatar answered Sep 22 '22 12:09

vadian