Boris R
Boris R

Reputation: 79

performSelector causes leak because not right type in objective c

I have the following code:

SEL moveAlongBoth = @selector(moveAlongX:andY:);
if ([p1 respondsToSelector:moveAlongBoth]) {
    [p1 performSelector: moveAlongBoth
             withObject: [NSNumber numberWithInt:1]
             withObject: [NSNumber numberWithInt:1]];
}

I am getting a "performSelector may cause leak" warning. But

[p1 moveAlongX:1 andY:1];

Works just fine.

I understand that I am getting the error because the values are set to (int) in the implementation and I am using NSNumber. Without changing the implementation, how would I go about declaring a number value to int (if possible)?

Upvotes: 1

Views: 30

Answers (2)

rob mayoff
rob mayoff

Reputation: 385600

Why can't you just do this:

if ([p1 respondsToSelector:@selector(moveAlongX:andY:)]) {
    [(id)p1 moveAlongX:1 andY:1];
}

By the way, the Cocoa naming convention would have you call this method moveAlongX:y:.

Upvotes: 1

Hermann Klecker
Hermann Klecker

Reputation: 14068

With regard to the second part. If you are in charge of the classes that may be the type of p1, then you could define a protocol with moveAlongBoth:: and instead of checking with performSelector check wit conformsToProtocol. Let's say the protocol's name is CanMoveAlong then you can cast it to

id <CanMoveAlong> canDo = (id<CanMoveAlong>)p1; 

after you checked conformity and directly invoke the method

[canDo moveAlongX:1 andY:1];

Doing so you achieve both, you get rid of the warning and you can pass int directly without using NSNumber.

Upvotes: 0

Related Questions