2011-10-09 72 views
1

我是Objective-C编程的初学者,我需要从另一个类中访问存储在NSMutableArray中的数据以填充TableView,但是我只能得到null。 我需要访问的变量是在下面的类:来自另一个类的访问变量

FunctionsController.h

#import <UIKit/UIKit.h> 

@interface FunctionsController : UIView { 
    @public NSMutableArray *placesNames;  
    NSMutableArray *placesAdresses; 
    NSMutableArray *placesReferences; 
    NSMutableArray *placesLatitudes; 
    NSMutableArray *placesLongitudes; 
    NSArray *list; 
} 
@end 

在这个其他类我试图访问数据,但我只得到空的结果。

SimpleSplitController.m

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; 
    } 
    FunctionsController *arrays = [[FunctionsController alloc] init]; 
    NSMutableArray *names = [arrays->placesNames]; 

    // Set up the cell... 
    cell.textLabel.text = [names objectAtIndex:indexPath.row]; 
    cell.textLabel.adjustsFontSizeToFitWidth = YES; 
    cell.textLabel.font = [UIFont systemFontOfSize:12]; 
    cell.textLabel.minimumFontSize = 10; 
    cell.textLabel.numberOfLines = 4; 
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap; 

return cell;  
} 

回答

3

的问题是在这里:

FunctionsController *arrays = [[FunctionsController alloc] init]; 
NSMutableArray *names = [arrays->placesNames]; 

首先你再次分配FunctionsController。这给你一个干净的新实例,其变量中没有数据。如果这个'init'没有把这些变量放在这些变量中,你就不会从它们那里得到任何东西。

我看到的第二个问题是您直接访问变量。我会使用属性来代替。

@property (nonatomic, retain) NSMutableArray *placesNames; 

并将其加入到您的FunctionsController.m:

@synthesize placesNames; 

然后你做这个访问属性:

NSMutableArray *names = arrays.placesNames; 
您在您的FunctionsController.h做这个声明属性

最后,我会建议您使用核心数据来存储该数据,因为它似乎应该属于一个SQL数据库。更多关于核心数据在这里:http://developer.apple.com/library/ios/#DOCUMENTATION/DataManagement/Conceptual/iPhoneCoreData01/Introduction/Introduction.html

+0

如何初始化数组变量? FunctionsController * array;只要? – CainaSouza

+0

如果你想让你的FunctionsController保存你的数据,并且仍然可以从任何类中调用它,而不必将它分配给一个变量,以便它保持实例化,你应该尝试在FunctionsController上使用Singleton模式。关于单身模式的信息在这里http://www.johnwordsworth.com/2010/04/iphone-code-snippet-the-singleton-pattern/ – raixer

1

这是你的问题:

FunctionsController *arrays = [[FunctionsController alloc] init]; 
NSMutableArray *names = [arrays->placesNames]; 

除非你在FunctionsController的init方法建立placesNames那么它要么是空的或为零。

请看目标-c上的singletons