Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing a singleton to create an array accessible by multiple views
    primarykey
    data
    text
    <p>It's a classic problem.</p> <p>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:</p> <ol> <li>Where do I instantiate my singleton object?</li> <li>Where do I instantiate my NSMutable array of objects?</li> <li>How do I refer to this array from anywhere within my project?</li> </ol> <p>All code and examples are greatly appreciated!</p> <p><strong>EDIT 1</strong></p> <p>This is what I have so far. I can't figure out though how to access this array of bananas correctly and consistently:</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; @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 </code></pre> <p><strong>EDIT 2</strong></p> <p>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 :(</p> <pre><code>- (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]; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload