Is there any way to specify what specific type of object can be contained within an NSMutableArray
?
有没有办法指定NSMutableArray中可以包含哪些特定类型的对象?
EDIT More specifically... Is there a way to restrict the class that the object must belong to?
编辑更具体地说......有没有办法限制对象必须属于的类?
2 个解决方案
#1
2
Well, you could always subclass NSMutableArray
but as everyone else has said, it is hard to imagine a good reason to do this....
好吧,你总是可以继承NSMutableArray的子类,但正如其他人所说的那样,很难想象这样做的一个很好的理由....
From Subclassing Notes in the docs you would basically have to over-ride the following functions and check for the proper class:
从文档中的子类注释中,您基本上必须覆盖以下函数并检查正确的类:
- insertObject:atIndex:
- addObject:
- replaceObjectAtIndex:withObject:
- the primitive methods of the NSArray class
NSArray类的原始方法
#2
1
You could check the class of the object before adding it to the array.
您可以在将对象添加到数组之前检查该对象的类。
NSMutableArray *myArray = [NSMutableArray alloc] init];
if ([someObject isKindOfClass:[ClassYouWantInArray class]]){
[myArray addObject:someObject];
}
#1
2
Well, you could always subclass NSMutableArray
but as everyone else has said, it is hard to imagine a good reason to do this....
好吧,你总是可以继承NSMutableArray的子类,但正如其他人所说的那样,很难想象这样做的一个很好的理由....
From Subclassing Notes in the docs you would basically have to over-ride the following functions and check for the proper class:
从文档中的子类注释中,您基本上必须覆盖以下函数并检查正确的类:
- insertObject:atIndex:
- addObject:
- replaceObjectAtIndex:withObject:
- the primitive methods of the NSArray class
NSArray类的原始方法
#2
1
You could check the class of the object before adding it to the array.
您可以在将对象添加到数组之前检查该对象的类。
NSMutableArray *myArray = [NSMutableArray alloc] init];
if ([someObject isKindOfClass:[ClassYouWantInArray class]]){
[myArray addObject:someObject];
}