简体   繁体   English

类对象到协议

[英]Class Object to Protocol

I have a model class fake Repository which implements a Delegate Method: 我有一个实现Delegate方法的模型类假存储库:

.h 。H

@interface FakeAccountRepository : NSObject <AccountRepositoryDelegate>
@end

.m .m

    @implementation FakeAccountRepository
-(id)init{
    if (self = [super init]) {
       // statements
    }
    return self;
}

This is the protocol and delegate: 这是协议和委托:

@protocol AccountRepositoryDelegate <NSObject>

@optional
- (NSArray *)accountRegistered;

@end

In the View Controller, what is the meaning of this : 在View Controller中,这是什么意思:

id <AccountRepositoryDelegate> fakeRepository = [[FakeAccountRepository alloc] init];

I mean " [[FakeAccountRepository alloc] init] " is returning an object of the FakeRepository class. 我的意思是“ [[FakeAccountRepository alloc] init] ”正在返回FakeRepository类的对象。 Then what is this assigning happening ?? 那这分配发生了什么??

The code: 编码:

[[FakeAccountRepository alloc] init];

obviously creates an instance of the FakeAccountRepository class. 显然会创建FakeAccountRepository类的实例。 And, as you know, this class happens to conform to the AccountRepositoryDelegate protocol. 而且,您知道,该类恰好符合AccountRepositoryDelegate协议。

The declaration: 声明:

id <AccountRepositoryDelegate> fakeRepository

is creating a variable named fakeRepository and its type is id <AccountRepositoryDelegate> . 正在创建一个名为fakeRepository的变量,其类型为id <AccountRepositoryDelegate> id means an object reference to any object type. id表示对任何对象类型的对象引用。 The <AccountRepositoryDelegate> of course references the AccountRepositoryDelegate protocol. <AccountRepositoryDelegate>当然引用了AccountRepositoryDelegate协议。 Together they mean that the variable can be of any object type as long as that object conforms to the AccountRepositoryDelegate protocol. 它们在一起意味着变量可以是任何对象类型,只要该对象符合AccountRepositoryDelegate协议即可。

Basically, id<SomeProtocol> means that you can assign any object that conforms to the given protocol. 基本上, id<SomeProtocol>意味着您可以分配符合给定协议的任何对象。

You can see plenty of examples of this in the iOS APIs. 您可以在iOS API中看到很多示例。 For example, the dataSource and delegate properties of UITableView are defined as id<UITableViewDataSource> and id<UITableViewDelegate> respectively. 例如, UITableViewdataSourcedelegate属性分别定义为id<UITableViewDataSource>id<UITableViewDelegate>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM