alexshafran
alexshafran

Reputation: 433

iOS: accept multiple object types as a paramenter (id)object?

I want to create a method that will accept a UIButton, UIImageView, or any other object as a parameter. I have tried the following using the id type,

-(void)shiftObject:(id)object {
      object.frame = CGRectMake(0, 0, 20, 20);
}

but the xcode static error checker flagged it right away. Is there a way that this can be done? I think I am on the right track using the id type, but I'm unsure where to go from here.

Upvotes: 1

Views: 579

Answers (2)

Pierre
Pierre

Reputation: 2019

You can cast your object to the correct type:

((UIButton*)object).frame = ...

or you can call the setter without the dot notation

[object setFrame:...];

You should check if your object is of the correct type before or if it responds to the selector you want to send.

Upvotes: 2

Evan Cordell
Evan Cordell

Reputation: 4118

You can't really use this with "any other object", just "any other object that has a frame property".

So, try casting to something with a frame, like UIView. All of the objects you mentioned inherit from UIView, and therefore have the frame property.

-(void)shiftObject:(id)object {
      ((UIView*)object).frame = CGRectMake(0, 0, 20, 20);
}

Upvotes: 3

Related Questions