Objective-C 通过协议调用 iOS 方法

发布于 2024-12-12 07:03:45 字数 586 浏览 5 评论 0原文

我正在为我的 iOS 应用程序解决有关协议的设计问题。现在我了解了用法,以及何时需要协议,并且我也了解它们类似于 C# 和 Java 中的接口。

可以通过协议本身调用方法吗?例如,在 C# 中,我可以执行以下操作:

public interface IInterface
{
    void SomeMethod();
    void SomeOtherMethod();
}


public class AClass : IInterface
{
    public void SomeMethod()
    {
        //Do something
    }

    public void SomeOtherMethod()
    {
        //Do something
    }
}


public class Program
{
    public void Main()
    {
         IInterface i = new AClass();
         i.SomeMethod();
    }
}

这在 Objective-C 中可能吗?还是我试图在 iOS 中强制采用 .NET 风格的方法?

I'm working on a design issue for my iOS app regarding protocols. Now I understand the usage, and when a protocol is required, and I also understand that they are analogous to interfaces in C# and Java.

Can you call methods through the protocol itself? For example, in C# I can do the following:

public interface IInterface
{
    void SomeMethod();
    void SomeOtherMethod();
}


public class AClass : IInterface
{
    public void SomeMethod()
    {
        //Do something
    }

    public void SomeOtherMethod()
    {
        //Do something
    }
}


public class Program
{
    public void Main()
    {
         IInterface i = new AClass();
         i.SomeMethod();
    }
}

Is this possible in Objective-C or am I trying to force a .NET style approach into iOS?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

万劫不复 2024-12-19 07:03:45
@protocol Protocol
- (void)someFunction;
@end

@interface A <Protocol>
@end

@implementation A
- (void) someFunction
{
    ....
}
@end

在其他一些地方

id<Protocol> a = [[A alloc] init];

[a someFunction];

[a release];
@protocol Protocol
- (void)someFunction;
@end

@interface A <Protocol>
@end

@implementation A
- (void) someFunction
{
    ....
}
@end

In some other place

id<Protocol> a = [[A alloc] init];

[a someFunction];

[a release];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文