数组在 Objective-C 中的表现如何?
我一直对数组抱有怀疑。
如果数组的计数为 7,并且我将第二个元素替换为“NULL”,那么它的计数仍然为 7 吗?
如果数组的计数为 7,并且我将最后一个元素替换为“NULL”,那么它的计数仍然为 7 吗?还是计数为 6?
我需要知道这种行为才能创建一个函数来删除数组的第一个元素(放置“0”),并将数组的其他元素交换到前面的一个位置。
- (void) eat {
[foodArray replaceObjectAtIndex:0 withObject:NULL];
for (int i = 0; i<[foodArray count]-1; ++i){
[foodArray replaceObjectAtIndex:i withObject:[foodArray objectAtIndex:i+1]];
}
[foodArray replaceObjectAtIndex:[foodArray count]-1 withObject:NULL];
}
那行得通吗?
(谢谢!)
编辑:我刚刚注意到第一行是不必要的,因为我稍后已经替换了第一个元素。我错了吗?
I've always had my doubts about Arrays.
If an Array's count is 7, and I replace the SECOND elements with 'NULL', does it still have count 7?
If an Array's count is 7, and I replace the LAST elements with 'NULL', does it still have count 7? Or will it have count 6?
I need to know this behavior to make a function that removes the first element of the Array (place '0'), and the other elements of the Array swap one place to the front.
- (void) eat {
[foodArray replaceObjectAtIndex:0 withObject:NULL];
for (int i = 0; i<[foodArray count]-1; ++i){
[foodArray replaceObjectAtIndex:i withObject:[foodArray objectAtIndex:i+1]];
}
[foodArray replaceObjectAtIndex:[foodArray count]-1 withObject:NULL];
}
Would that work?
(Thanks!)
Edit: I've just noticed the first line isn't necessary, as I'm already replacing the first element later. Am I wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你想从数组中删除一个对象,只需使用[foodArray removeObjectAtIndex:]。你这样做的方式只是在数组中留下一个空值。
If you want to remove an object from an array, just use [foodArray removeObjectAtIndex:]. The way you're doing it you're just leaving a null value in the array.
只需删除该项目:
为了添加/删除数组元素,数组必须是可变的:
NSMutableArray
,因此 foodArray 必须是NSMutableArray
。Just remove the item:
Inorder to add/remove array elements the array must be mutable:
NSMutableArray
so foodArray must be aNSMutableArray
.一般来说,尝试在数组中保留 NULL 是个坏主意。
如果您需要使用某种占位符 - 最好使用 NSNull 类的实例。
稍后您可以使用类名检查来检查对象的类型:
Trying to keep NULL in an array is bad idea in general.
If you need to use some kind of placeholder - it's better to use an instance of NSNull class.
Later you can check type of the object using class name check: