return CGRect on selector causes crash

361 views Asked by At

I've the following code:

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // Does not crash
    //[self performSelector:@selector(dummyRectValue)];

    // Does not crash
    [self performSelector:@selector(dummyPoint)];

    // Crash
    [self performSelector:@selector(dummyRect)];

}

- (NSValue*) dummyRectValue
{
    return [NSValue valueWithCGRect:CGRectMake(0.0f, 0.0f, 0.0f, 0.0f)];
}

- (CGRect) dummyRect
{
    return CGRectMake(0.0f, 0.0f, 0.0f, 0.0f);
}

- (CGPoint) dummyPoint
{
    return CGPointMake(0.0f, 0.0f);
}

@end

Currently, calling [self performSelector:@selector(dummyRect)] causes a crash.

Any help understanding what I'm doing wrong ?

Thanks in advance,

3

There are 3 answers

5
BHASKAR On

In objective-C you can not return CGRect. so you have to CGRect convert into NSValue. so you get the crash report. This is a fundamental limitation of Objective-C — a variable cannot sometimes hold an object and sometimes a primitive value. The best workaround is to return an NSNumber or NSValue object wrapping the real value you want to return.

1
Onik IV On

perfomSelector is a NSObject method. You can find this in Apple doc:

   - (id)performSelector:(SEL)aSelector

You can see, it only returns objects (id), and you are trying it returns a C structure (CGRect)

You can do this:

   [self dummyRect];
2
Suhit Patil On

in objective-C you can not send CGRect as a parameter, so you need convert CGRect to NSValue.

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // Does not crash
    //[self performSelector:@selector(dummyRectValue)];

    // Does not crash
    [self performSelector:@selector(dummyPoint)];

    // Crash
    [self performSelector:@selector(dummyRect)];

}


 //Return CGRect as NSValue
    - (NSValue *)dummyRect
    {
        return [NSValue valueWithCGRect:CGRectMake(0.0f, 0.0f, 0.0f, 0.0f)];
    }