简体   繁体   中英

After fetching UITableView Section and Row… what does this code do?

Can anyone explain me what this code does after getting 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];
  }

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM