为什么NSArray不为不存在的索引返回NULL? [英] Why Doesn't NSArray return NULL for nonexistent indexes?
问题描述
我理解Objective C的一个特别的事情是你可以发送消息到NULL,它会忽略它们而不是崩溃。
为什么是NSArray不只是返回一个NULL对象,如果请求的索引超出边界而不是引起NSRangeException?
我期望从Objective C和NSArray如下:
NSArray * array = [NSArray arrayWithObjects:@Object 1,@Object 2 Object 3,nil];
for(int i = 0; i <5; i ++){
NSString * string = [array objectAtIndex:i];
if(string){
NSLog(@Object:%@,string);
}
}
允许我访问数组的索引, t包含对象并简单地返回NULL。然后我可以检查对象是否存在。我可以在其他地方这样做,如检查对象是否已实例化。
NSArray * array;
if(!array){
array = [NSArray array];
}
我发现这是一个基于理论的问题,但我很好奇) / p>
到nil的邮件是语言级别的功能,而不是框架API功能。
NSArray
(和其他类)抛出一个异常来指示程序员错误是一个有意识的设计决策,当API被设计时(〜1993)。正如Kevin和Richard所指出的, nil eats消息
是没有错误的,而超出范围
的错误输入。
你在哪里画线?应该 substringWithRange:
接受任何旧的输入? setObject:atIndex:
?
通过使NSArray @throw对
indexOfObject:
它使API一致; 任何超出范围的索引(或范围)将会 @throw
。 The way I understand it one of the things special about Objective C is that you can send messages to NULL and it will just ignore them instead of crashing.
Why is it that NSArray doesn't just return a NULL object if the index requested is out of bounds instead of causing a NSRangeException?
What I would expect from Objective C and NSArray is the following.
NSArray *array = [NSArray arrayWithObjects:@"Object 1", @"Object 2", @"Object 3", nil];
for (int i = 0; i < 5; i++) {
NSString *string = [array objectAtIndex:i];
if (string) {
NSLog(@"Object: %@",string);
}
}
Allowing me to access indexes of the array with don't contain objects and simply returning NULL. Then I can check if the object exists. I can do this in other places such as checking if the object has been instantiated.
NSArray *array;
if (!array) {
array = [NSArray array];
}
I realize this is a theory based question but I'm curious :)
Messages to nil is a language level feature, not a framework API feature.
That NSArray
(and other classes) throw an exception to indicate programmer error is a conscious design decision that was made when the API was designed (~1993). As both Kevin and Richard indicate, nil eats message
is not erroneous in anyway whereas out of bounds
is very much a case of erroneous input.
Where would you draw the line? Should substringWithRange:
accept any old input? How about setObject:atIndex:
?
By making NSArray @throw on bounds exceptions for indexOfObject:
it makes the API consistent; any index (or range) that is out of bound will @throw
.
这篇关于为什么NSArray不为不存在的索引返回NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!