It's a classic problem.
I would like to access an array of objects from anywhere within my app. I would also like to do this using a singleton. My questions are:
- Where do I instantiate my singleton object?
- Where do I instantiate my NSMutable array of objects?
- How do I refer to this array from anywhere within my project?
All code and examples are greatly appreciated!
EDIT 1
This is what I have so far. I can't figure out though how to access this array of bananas correctly and consistently:
#import <Foundation/Foundation.h>
@interface Singleton : NSObject {
NSMutableArray *bananas;
}
@property (nonatomic, retain) NSMutableArray *bananas;
@end
#import "Singleton.h"
static Singleton *mySingleton;
@implementation Singleton
@synthesize bananas;
#pragma mark SingletonDescption stuff
+ (Singleton *)mySingleton
{
if(!mySingleton){
mySingleton = [[Singleton alloc]init];
}
return mySingleton;
}
+ (id)allocWithZone:(NSZone *)zone
{
if (!mySingleton) {
mySingleton = [super allocWithZone:zone];
return mySingleton;
} else {
return nil;
}
}
- (id)copyWithZone:(NSZone*) zone
{
return self;
}
- (void)release
{
// NO OP
}
@end
EDIT 2
This is how I'm trying to use my singleton object to have an array of objects placed in a table cell. Nothing is happening and the table cell comes up blank :(
- (id)init
{
[super initWithStyle:UITableViewStylePlain];
// bananas = [[NSMutableArray alloc] init];
Singleton *mySingleton = [[Singleton alloc]init];
mySingleton.bananas = [[NSMutableArray alloc]init];
UIImage *imageA = [UIImage imageNamed:@"A.png"];
UIImage *imageB = [UIImage imageNamed:@"B.png"];
UIImage *imageC = [UIImage imageNamed:@"C.png"];
Banana *yellowBanana = [[Banana alloc] initWithName:@"Yellow" description:@"Beautiful" weight:22.0 icon:imageA];
Banana *greenBanana = [[Banana alloc] initWithName:@"Green" description:@"Gorgeous" weight:12.0 icon:imageB];
Banana *rottenBanana = [[Banana alloc] initWithName:@"Rotten" description:@"Ugly" weight:8.0 icon:imageC];
[mySingleton.bananas addObject:yellowBanana];
[mySingleton.bananas addObject:greenBanana];
[mySingleton.bananas addObject:rottenBanana];
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…