2011-10-09 71 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