Can anyone explain me what this code does after getting NSArray.开发者_C百科...
- (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];
}
I am getting NSArray of Section... then how can we assign the values of the row to a Class??
Here the array samples contains the objects of type Class. You can create an instance of class directly using a class name or by using a Class object/variable. For example,
/* 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];
Your code uses the second way to allocate the view controller object from the class object returned by [samples objectAtIndex:indexPath.row].
After getting the array, it retrieves a particular Class
using :
Class clazz = [samples objectAtIndex:indexPath.row];
and then it instantiates a UIViewController
object using the class, and return that object :
UIViewController *instance = [[clazz alloc] initWithNibName:nil bundle:nil];
return [instance autorelease];
精彩评论