本文介绍了Objective C - 子类中的窄实例变量类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以缩小子类中允许的ivar类型。这样的事情:

Is it possible to narrow the allowed type of an ivar in a subclass. Something like this:

@interface person: NSObject {
  NSArray *friendArray;
}

@interface mutablePerson: person {
  NSMutableArray *friendArray;
}

我只是尝试了那个确切的代码,Xcode给了我一个编译错误。我想知道是否有办法绕过它。

I just tried that exact code, and Xcode gave me a compile error. I'm wondering if there is a way around it.

我正在研究的项目会有很多这种情况。我知道我可以使用强制转换来使代码工作。但如果我这样做,我会做很多演员表,我想知道是否有更好的方法。

The project I am working on is going to have a lot of this sort of situation. I understand that I can use casts to make the code work. But I will be making an awful lot of casts if I do that, and I'm wondering if there is a better way.

推荐答案

我结束了覆盖setter以声明正在设置的对象是合适的类型,并创建一个新的只读getter,如下所示:

I ended overriding the setter to assert that the object being set is of the appropriate type, and creating a new read-only getter, like this:

@interface MutablePerson {
}

@property (readonly) NSMutableArray *mutableFriendArray;

@implementation MutablePerson

-(NSMutableArray *) mutableFriendArray {
  NSMutableArray *ret = (NSMutableArray *)[super friendArray];
  NSAssert ([ret isKindOfClass: [NSMutableArray class]], @"array should be mutable");
  return ret;
}

-(void) setFriendArray: (NSMutableArray *) array {
  NSAssert ([array isKindOfClass: [NSMutableArray class]], @"array should be mutable");
  [super setFriendArray: array];
}

这篇关于Objective C - 子类中的窄实例变量类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 08:08