如何在Objective-C中将一个类的对象分配给其他类?

时间:2023-01-15 15:08:29

how to assign object of interface to a protocol's object? i've a protocolA and protocolB. all the methods of both the protocols is implemented in MyClass.How to restrict the access to only protocolA's methid and protocolB's methods ?Coding is done in Objective-C for iPhone application.

如何将接口对象分配给协议的对象?我有一个protocolA和protocolB。两个协议的所有方法都是在MyClass中实现的。如何限制只访问protocolA的methid和protocolB的方法?编码是在Objective-C中为iPhone应用程序完成的。

1 个解决方案

#1


2  

On object creation you can just do this:

在对象创建上,您可以这样做:

id <protocolA> protocolAObject = [[MyClass alloc] init];

Now, unless you use an explicit cast, you can't use protocolB methods.

现在,除非使用显式强制转换,否则不能使用protocolB方法。

You can also cast objects of class MyClass to either protocolA or protocolB like this:

您还可以将类MyClass的对象强制转换为protocolA或protocolB,如下所示:

MyClass *myClassObject = [[MyClass alloc] init];
id <protocolB> protocolBObject = (id <protocolB>) myClassObject;

#1


2  

On object creation you can just do this:

在对象创建上,您可以这样做:

id <protocolA> protocolAObject = [[MyClass alloc] init];

Now, unless you use an explicit cast, you can't use protocolB methods.

现在,除非使用显式强制转换,否则不能使用protocolB方法。

You can also cast objects of class MyClass to either protocolA or protocolB like this:

您还可以将类MyClass的对象强制转换为protocolA或protocolB,如下所示:

MyClass *myClassObject = [[MyClass alloc] init];
id <protocolB> protocolBObject = (id <protocolB>) myClassObject;