我有一个单例类,其中包含一个 NSDictionary 数组(其中 5 个)。我需要在不同的 ViewController 中显示这些数据(我正在使用 Storyboard)。
如果我从数组中提取数据,我可以访问数据,但现在我需要从 NSDictionary 数组中提取数据。我想出了这条线:
cell.textLabel.text = [[[[Singleton sharedInstance] movies] objectAtIndex:indexPath.row] objectForKey:@"title"];
但这似乎不起作用。
有任何想法吗?我将把我的 Singleton 类和我的 TableView 类:
单例.h
#import <Foundation/Foundation.h>
#import "AppDelegate.h"
@interface Singleton : NSObject {
NSDictionary *batman;
NSDictionary *superman;
NSArray *superheoes;
}
@property(nonatomic,retain) NSDictionary *batman;
@property(nonatomic,retain) NSDictionary *superman;
@property(nonatomic,retain) NSArray *superheroes;
+ (Singleton *) sharedInstance;
+ (AppDelegate *) sharedAppDelegate;
@end
单身人士.m
#import "Singleton.h"
@implementation Singleton
@synthesize batman, superman;
+ (Singleton *) sharedInstance {
//The instance of this class is store here
static Singleton *myInstance = nil;
// We check to see if an instance already exists
if (nil == myInstance) {
myInstance = [[[self class] alloc] init];
}
return myInstance;
}
-(id) init {
if (self=[super init]) {
batman = [[NSDictionary alloc] initWithObjectsAndKeys:
@"name", @"Back to the Future",
@"year", @"1985", nil];
superman = [[NSDictionary alloc]initWithObjectsAndKeys:
@"name", @"Superman",
@"year", @"1990", nil];
superheroes = [NSArray arrayWithObjects:batman,superman, nil];
}
return self;
}
#pragma mark access to app delegate etc.
+ (AppDelegate *) sharedAppDelegate; {
return (AppDelegate*)[[UIApplication sharedApplication] delegate];
}
@end
超级英雄数据库.m
#import "SuperheroesDatabase.h"
#import "Singleton.h"
@interface SuperheroDatabase ()
@end
@implementation MovieDatabase
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [[[[Singleton sharedInstance] movies] objectAtIndex:indexPath.row] objectForKey:@"name"];
//cell.detailTextLabel.text = [NSString stringWithFormat:@"row %i", indexPath.row];
return cell;
}