I have written a protocol in Objective-C, named BHIDataFormatter, which is implemented by BHCsvDataFormatter, BHJsonFormatter, and BHXmlFormatter classes.
As a .NET developer primarily, the required instance can be obtained via:
IDataFormatter formatter;
if (csv) formatter = new CsvDataFormatter();
else if (json) formatter = new JsonFormatter();
else if (xml) formatter = new XmlDataFormatter();
else throw SomeException("Cripes");
Basically, how can I do the same in Objecive-C? I have tried, although BHIDataFormatter is an “unknown type”:
BHIDataFormatter* formatter;
if (csv) formatter = [[BHCsvDataFormatter alloc] init];
else if (json) formatter = [[BHJsonDataFormatter alloc] init];
else if (xml) formatter = [[BHXmlDataFormatter alloc] init];
else [[NSException exceptionWithName:@"SomeException" reason:@"Cripes" userInfo:nil] raise];
The following seems to work, although it seems too generic (I would rather specifically use BHIDataFormatter explicitly):
Protocol* formatter = [[CsvDataFormatter alloc] init];
You need to declare the variable as type
idthat conforms to the protocolThat is
idis a pointer to any object andyou are also claiming that the object will conform to
BHIDataFormatter