I have an array which contains NSRange
elements.
Now i can get the last range element of the array using [resultArray lastObject]
.
When i access the last element, It returns some unknown object. (Which means Unknown class)
Now i want to cast the object into NSRange
. How to do it?
My code is:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:paraStartRegEx options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *matches = [regex matchesInString:content options:0 range:NSMakeRange(0, [content length])];
NSObject *obj = [matches lastObject];
How can I convert this object to NSRange
?
If you had read the documentation, you would have noticed that the matchesInString:options:range:
method of NSRegularExpression
returns an NSArray
of NSTextCheckingResult
objects, not NSRange
s, so it's no wonder that you couldn't get them out directly.
Additionally (and you should remember this for the future, as it is an important distinction), NSRange
is a C struct
, not an Objective-C object. This means that it cannot be directly stored in NSArray
s or other Objective-C object containers. NSArray
, NSDictionary
, and other Objective-C classes that are used for storing objects can only store objects of Objective-C types , ie, objects that are an instance of a Class
and can have messages sent to them with [object method]
.
Now to get back to your question, the array you are getting from matchesInString:options:range:
contains NSTextCheckingResult
objects, which contain a lot more information than just the range of the match, so you can't just cast them to an NSRange
; you need to access the range
property of the object to get what you want:
NSTextCheckingResult *result = [matches lastObject];
NSRange range = [result range];
NSRange is a C struct.
NSArray does not hold C types, only objects.
NSRegularExpression returns a match NSArray that contains objects of NSTextCheckingResult type.
NSTextCheckingResult has a range property that returns the range of a match.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.