objectAtIndex在数组中使用两次

时间:2015-06-29 12:16:24

标签: ios objective-c

我一直在研究以下tutorial,并遇到了这段代码:

cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", [[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:indexOfFirstname], [[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:indexOfLastname]];

以下是我不理解的部分:

[[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:indexOfFirstname]

objectAtIndex在这里使用了两次。我不明白这里发生了什么。 我试着研究阵列是如何工作的,我明白了。但是这条线让我难过

4 个答案:

答案 0 :(得分:2)

实际上它很直接,首先从arrPeopleInfo中选择一个对象,然后从结果数组中选择另一个对象。您可以将其分为两步,以便更好地理解它:

// The variable names (and the NSString type) are speculative here 
NSArray *person = [self.arrPeopleInfo objectAtIndex:indexPath.row];
NSString *name  = [person objectAtIndex:indexOfFirstname];

// and to complete your example...
NSString *lastName = [person objectAtIndex:indexOfLastname];

最终导致:

cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", name, lastName];

PS。另一种说明嵌套数组访问的方法就是这样(一个相当愚蠢的例子,但你明白了......):

NSArray *a  = @[ @[@"a", @"b"], @[@"c", @"d"] ]; // An array with 2 arrays
NSString *b = a[0][1]; // Get the object at 0 [a,b] then the object at 1 (b)
NSLog(@"%@", b); // Prints b

答案 1 :(得分:1)

你的数组必须是这样的:

(
   (
      "firstname 1",
      "lastname 1"
   ),
   (
      "firstname 2",
      "lastname 2"
   ),
   (
      "firstname 3",
      "lastname 3"
   ),
   (
      "firstname 4",
      "lastname 4"
   )
)

现在让我们讨论一下[[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:indexOfFirstname]

这行代码包含两个语句,我们可以这样说:

NSArray * personArray = [self.arrPeopleInfo objectAtIndex:indexPath.row];
NSString * fName = [personArray objectAtIndex:indexOfFirstname];

如果indexPath.row为2 personArray,则会为您提供以下数组,即self.arrPeopleInfo的第3个对象:

   (
      "firstname 3",
      "lastname 3"
   )

现在第二个声明:indexOfFirstname将为0(零)。因此fNamefirstname 3personArray的第一个对象。

希望这会对你有帮助......

答案 2 :(得分:0)

看起来阵列中有一个数组。在Objective-C中编程是非常令人困惑的,但在C中非常正常 我会在数组中使用NSDictionary。

答案 3 :(得分:-1)

arrPeopleInfo是一个多维数组。 (数组中的数组。普通数组的每个对象,itselve是一个数组。)

所以你有例如:

multidimensionalArray:
1  - 1, 2, 3, 4, 5, 6
2  - 6, 5, 4, 3, 2, 3
3  - 2, 3, 4, 2, 3, 2
4  - 2, 3, 2, 1, 4, 3
5  - 2, 3, 2, 1, 3, 4
6  - 5, 3, 2, 3, 4, 5

[multidimensionalArray objectAtIndex:1] = 6,5,4,3,2,3

[[multidimensionalArray objectAtIndex:1] objectAtIndex:2] = 4