Tuesday 15 February 2011

objective c - Why use (id) in a method signature when (NSObject *) would be more precise? -


Whenever I apply a method to my own code that can accept or return items from more than one class I always try to use the most specific superclass is available. For example, if I was going to implement a method which could return an NSArray * or an NSDictionary * based on its input, then I would use that method I give NSObject * of a return type because all this Sector general common superclass Here is an example:

  @ interface Maypars () - (BOOL) stringExpressesKeyValuePairs: (NSString *) string; - (BOOL) stringExpressesAListOfEntities: (NSString *) string; - (NSArray *) parseArrayFromString: (NSString *) string; - (NSDictionary *) parseDictionaryFromString: (NSString *) string; @end @implementation MyParser - (NSObject *) parseString: (NSString *) string {if ([self stringExpressesKeyValuePairs: string]) {return parseDictionaryFromString: string]; } And if ([self string accresololostoffics: string]) {returns [self-purserefrostration: string]; }} // etc ... @end  

I Foundation and noted several cases in other APIs which Apple uses in some ways the signatures (ID) when (Ansobaijekt *) Will be more precise. For example, here is a method of NSPropertyListSerialization:

  + (id) propertyListFromData: (NSData *) data Priwartnshiltaopsn: (NSPropertyListMutabilityOptions) opt format: (NSPropertyListFormat *) format Trutidiskripshn: (NSString * *) error string  

type possible drawback to this method Ansdita, Ansstiing, Ansaara, Ansdapshn, Ansdit and Ansanmber. It seems that there will be a better option than a return type (NSBact *) (ID), because the caller will then be able to call the NSOB method such as maintaining it without type-cast.

I generally try to emulate idioms established by official settings, but I should also understand what has been inspired by them. I am sure that the use of such cases Apple (ID) to some valid reasons, but I will tell the compiler to use not see it my ID is that it will be an object of unknown type I

using NSObject Compiler you will only be required to use the messages available to NSObject. So ... if you know that an array has been returned and it is placed as an ID, then you can call the objectautandex: without compiler warnings. While returning with an artist of NSObject, you will receive warnings.


No comments:

Post a Comment