user732274
user732274

Reputation: 1069

ObjC: restrict id to some types

In Objective-C, is it possible to restrict id to just a few types? I want to write a method having an id parameter, but this method applies only to some ObjC types: using id could lead to runtime errors. Is there any LLVM convention or something like that?

Upvotes: 1

Views: 185

Answers (3)

user529758
user529758

Reputation:

"restricting" id is not something Objective-C has. Anyways, if you pass an object of which the type doesn't match the type specified in the method declaration, you would only get a warning and not a compiler error (unless you compile using -Werror), so the compiler can't really prevent you from doing this.

Yes, this is runtime-error-prone, but that's how Objective-C works. One thing you should do is documenting which types are accepted.

One thing you can do is checking the type at runtime, either by using the isKindOfClass: or isMemeberOfClass: methods of NSObject. Also, if there are a common set of messages the object should respond to, you can wrap them into a protocol and require an expression of type id <MyProtocol>.

Upvotes: 1

Tom
Tom

Reputation: 1349

As long as you're dealing with objects, you can ask for it's class:

id anId;

if ([anId isKindOfClass:[NSNumber class]]) {
    ...
}

Upvotes: 1

Alessandro Vendruscolo
Alessandro Vendruscolo

Reputation: 14875

id is a generic Objective-C object pointer, ie it means any object.

The only way you could restrict the type would be using protocols:

id <myProtocol>

Therefore, in this way, you point to any object which adopts the myProtocol protocol.

Upvotes: 1

Related Questions