简体   繁体   中英

iOS Table View Datasource in Different Class

I have a simple iOS app in which one class called Dictionary (.m and .h) has several functions for building an NSArray of NSDictionary objects and then functions to manipulate that data structure. I have a UITableViewController class that has the table view delegate methods, but I can't figure out how to create an instance of the Dictionary class in that UIViewController in order to be able to have all of the delegate methods talk to that instance of the class (eg when i call Dictionary *dictionary = [[Dictionary alloc] init] in the viewDidLoad method, I can't access any of that instance in the cellForRowAtIndexPath delegate method. New to iOS programming and feeling very frustrated with it! Any help would be greatly appreciated.

Sounds like you need to declare dictionary as a member variable of your class. There are several ways to do this. The quickest is to put the following above the @implementation call in your .m file of your table view controller.

@interface nameOftableViewControllerClass(){
    Dictionary *dictionary;
}
@end

Make sure to replace nameOftableViewControllerClass with the actual name of your view controller class. Then, in view did load. you can call the following

dictionary = [[Dictionary alloc] init];

Then in the cellForRowAtIndexPath you can call any functions on the dictionary object. Don't forget to put a release call in the dealloc method of your table view controller.

-(void) dealloc {
     [dictionary release];
     [super dealloc];
}

hope this helps, hit my up if you have any more problems

The dictionary variable you declared that way is local to the viewDidLoad method. Instead, declare it as property of the ViewController, assign the Dictionary to it and then access it in your delegate methods (eg self.dictionary = [[Dictionary alloc] init] ).

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