获取UITableView Section和Row后...这段代码有什么作用?

时间:2011-07-20 12:07:10

标签: iphone ios cocoa-touch uitableview uiview

任何人都可以解释一下这段代码在获得NSArray后的作用....

- (UIViewController *)sampleForIndexPath:(NSIndexPath *)indexPath {

    NSArray *samples = [samples_ objectAtIndex:indexPath.section];
    Class clazz = [samples objectAtIndex:indexPath.row];
    UIViewController *instance = [[clazz alloc] initWithNibName:nil bundle:nil];
    return [instance autorelease];
  }

我正在获取Section的NSArray ...那么我们如何将行的值分配给Class?

2 个答案:

答案 0 :(得分:2)

此处数组示例包含类型的对象。您可以使用类名或使用 Class 对象/变量直接创建类的实例。例如,

/* One Way */

// Create an instance of MyViewController deirectly
UIViewController *vc = [[MyViewController alloc] init];

/* Another Way */

// The following line returns a class object
Class cls = NSClassFromString(@"MyViewController");
// The below is just for an example. This also returns a class object 
Class cls = [MyViewController class]; 
// Create an instance of MyViewController from the class object
UIViewController *vc = [[cls alloc] init];

您的代码使用第二种方式 [samples objectAtIndex:indexPath.row] 返回的类对象中分配视图控制器对象。

答案 1 :(得分:1)

获取数组后,它使用:

检索特定的Class

Class clazz = [samples objectAtIndex:indexPath.row];

然后使用该类实例化一个UIViewController对象,并返回该对象:

UIViewController *instance = [[clazz alloc] initWithNibName:nil bundle:nil];
return [instance autorelease];