以下是一些苹果类的几种方法:当一个方法可以返回子类时返回类型应该是什么?
- (NSManagedObject *)objectWithID:(NSManagedObjectID *)objectID;
- (UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier;
+ (id)insertNewObjectForEntityForName:(NSString *)entityName inManagedObjectContext:(NSManagedObjectContext *)context
这是合理的预期,所有这些方法返回的返回类型的子类。由于这个原因,返回的对象通常被分配给一个预期类型的变量,例如:
BCCustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[BCCustomTableViewCell cellIdentifier]];
这使得编译器不高兴;铸造解决了这一点,但铸造这样脏:
BCCustomTableViewCell *cell = (id)[tableView dequeueReusableCellWithIdentifier:[BCCustomTableViewCell cellIdentifier]];
然而,当返回类型是id
,这个转换可以被删除,尽管某些类型的安全成本,导致我的代码是清洁:
BCPerson *person = [NSEntityDescription insertNewObjectForEntityForName:BCPersonEntityName inManagedObjectContext:context];
就我个人而言,我更喜欢当返回类型为id
。苹果是否有任何理由选择其中一种方法,还是仅仅是由于开发人员偏好编写这些方法?
铸造是肮脏的,但有方法返回`ID`脏! – 2011-01-06 11:39:00