MainakChoudhury
MainakChoudhury

Reputation: 524

Class Object to Protocol

I have a model class fake Repository which implements a Delegate Method:

.h

@interface FakeAccountRepository : NSObject <AccountRepositoryDelegate>
@end

.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 :

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

I mean "[[FakeAccountRepository alloc] init]" is returning an object of the FakeRepository class. Then what is this assigning happening ??

Upvotes: 0

Views: 20

Answers (1)

rmaddy
rmaddy

Reputation: 318934

The code:

[[FakeAccountRepository alloc] init];

obviously creates an instance of the FakeAccountRepository class. And, as you know, this class happens to conform to the AccountRepositoryDelegate protocol.

The declaration:

id <AccountRepositoryDelegate> fakeRepository

is creating a variable named fakeRepository and its type is id <AccountRepositoryDelegate>. id means an object reference to any object type. The <AccountRepositoryDelegate> of course references the AccountRepositoryDelegate protocol. Together they mean that the variable can be of any object type as long as that object conforms to the AccountRepositoryDelegate protocol.

Basically, id<SomeProtocol> means that you can assign any object that conforms to the given protocol.

You can see plenty of examples of this in the iOS APIs. For example, the dataSource and delegate properties of UITableView are defined as id<UITableViewDataSource> and id<UITableViewDelegate> respectively.

Upvotes: 1

Related Questions