Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a method return an NSRange?

I have a method that returns an NSRange. When I call this method from outside the class I get a compile error.

NSRange tmpRange;
tmpRange = [phrase rangeInString:searchString forString:theLetter goingForward:YES];
return tmpRange.location == -1;

in the .h file:

#import <Foundation/Foundation.h>


@interface Phrase : NSObject {

}
- (NSRange) rangeInString:(NSString *) tgt forString:(NSString *) find goingForward:(BOOL) fwd;  

@end

This method is called within the Phrase object by other methods without problems. The compiler says 'incompatible types in assignment'.

Can anyone explain this to me? I assume it has to do with returning an NSRange/struct type value generated outside the object, but I don't know why it works in one place and not the other.

like image 877
Dan Donaldson Avatar asked Aug 29 '26 07:08

Dan Donaldson


1 Answers

Of course a method can return NSRange. But returning structures require special attention to the compiler because how the method is invoked is usually different (objc_msgSend_stret vs. objc_msgSend).

Please make sure you declare phrase as

Phrase* phrase = ...;

so that the compiler knows -rangeInString:… is returning an NSRange, instead of

id phrase = ...;

(Also, since you don't show which line the compiler errors, make sure the function using return … == -1; is returning a BOOL not NSRange.)

like image 190
kennytm Avatar answered Aug 30 '26 23:08

kennytm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!