简体   繁体   English

不同类别的iOS表视图数据源

[英]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. 我有一个简单的iOS应用程序,其中一个名为Dictionary (.m和.h)的类具有用于构建NSDictionary对象的NSArray的几个函数,然后用于操纵该数据结构的函数。 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. 我有一个具有表视图委托方法的UITableViewController类,但是我不知道如何在该UIViewController中创建Dictionary类的实例,以便能够使所有委托方法都与该实例的实例进行对话。类(例如,当我在viewDidLoad方法中调用Dictionary *dictionary = [[Dictionary alloc] init]时,我无法在cellForRowAtIndexPath委托方法中访问该实例中的任何一个。iOS编程的cellForRowAtIndexPath ,对此感到非常沮丧!任何帮助将不胜感激。

Sounds like you need to declare dictionary as a member variable of your class. 听起来您需要将dictionary声明为类的成员变量。 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. 最快的方法是将以下内容放在表视图控制器的.m文件中的@implementation调用上方。

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

Make sure to replace nameOftableViewControllerClass with the actual name of your view controller class. 确保将nameOftableViewControllerClass替换为视图控制器类的实际名称。 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. 然后,可以在cellForRowAtIndexPath中调用字典对象上的任何函数。 Don't forget to put a release call in the dealloc method of your table view controller. 不要忘记将释放调用放入表视图控制器的dealloc方法中。

-(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. 您以这种方式声明的字典变量是viewDidLoad方法的局部变量。 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] ). 相反,将其声明为ViewController的属性,为它分配Dictionary,然后在您的委托方法中访问它(例如self.dictionary = [[Dictionary alloc] init])。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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