gpt4 book ai didi

ios - 如何使用 NSRange 创建 NSArray 的子数组?

转载 作者:IT王子 更新时间:2023-10-29 08:04:28 25 4
gpt4 key购买 nike

我有一个包含内容的数组。像往常一样,它包含 20 个对象。我想在 Tableview 中将同一个数组分成两部分。我正在尝试在当前数组中使用 NSMake 来实现它。例如,我需要进入第一个 tableview 部分 3 行,第二个将包含所有其余部分(17 行)。

switch (section) {
case 0:
return
[[array subarrayWithRange:NSMakeRange(3, 8)] count];
// in this line, it always takes from the first object in array, despite I told hime start from 3 (If I understand right, how to works NSMakeRange)
break;
case 1:
return
[[array subarrayWithRange:NSMakeRange(9, 19)] count];
// here my app is crashing with an error
//*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSArray subarrayWithRange:]: range {9, 19} extends beyond bounds [0 .. 19]'
default:
break;
}

有人可以帮我吗?

最佳答案

NSMakeRange 被定义为 (startingIndex, length),而不是 (start, end) 这看起来像是您尝试使用的方式

因此,如果您需要前 3 个对象,那么其余的对象将如下所示:

switch (section) {
case 0:
// This returns objects 0-2 in the array
return [array subarrayWithRange:NSMakeRange(0, 3)];
case 1:
// This returns objects 3-20 in the array
return [array subarrayWithRange:NSMakeRange(3, 17)];
default:
break;
}

编辑:根据您的评论,您实际上是在寻找要返回的部分中行数的计数。由于您使用的是固定行数,因此您可以在 case 语句中返回实际行数。

switch (section) {
case 0:
// This returns the count for objects 0-2 in the array
return 3;
case 1:
// This returns the count for objects 3-20 in the array
return 17;
default:
break;
}

您实际上不需要使用[subarrayWithRange],也不需要使用NSMakeRange。如果你确实需要在某个时候引用实际的数组,你将得到一个 NSIndexPath 对象,你可以使用它从你的数组中获取对象。您将需要使用 section 和 row 属性。

编辑:NSRange -> NSMakeRange

关于ios - 如何使用 NSRange 创建 NSArray 的子数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19597034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com