Alexander Kiefer
Alexander Kiefer

Reputation: 556

iOS: Method Return Type should be sub-class of class X

I have a class called "BaseEntry" and some specific classes like "EntryFoo" and "EntryBar" which are subclasses from "Base Entry".

Now there is a function getEntry which should return a Object which is subclass of BaseEntry. In Java this wouldn't be a problem but I have no idea how to fix this in Objective-C for iOS.

Thanks for your help! Alex

Upvotes: 2

Views: 1381

Answers (2)

Stig Brautaset
Stig Brautaset

Reputation: 2632

The standard way to do this in Objective-C is to just return an object of type 'id'; think of it as Object in Java. However, id is slightly nicer in that you can assign the return value to a typed value without a cast.

To clarify, your options are:

// Assuming -(BaseEntry*)getEntry;
id entry = [obj getEntry];
[entry messageOnlyOnFooEntry];

// Assuming -(BaseEntry*)getEntry; - note cast required
FooEntry *entry = (FooEntry*)[obj getEntry];
[entry messageOnlyOnFooEntry];

// Assuming -(id)getEntry; - no cast required
FooEntry *entry = [obj getEntry];
[entry messageOnlyOnFooEntry];

Upvotes: 3

chwi
chwi

Reputation: 2802

BaseEntry gE = [[BaseEntry alloc] init]; // Allocate and init a BaseEntry object
returnGetEntryHere = [ge getEntry]; // This will execute getEntry which is a method in BaseEntry

Have you tried anything until now? If you post some code maybe people could help you out with your misunderstandings and shortcomings regarding your objective-c project

Upvotes: 0

Related Questions