Note that there are some explanatory texts on larger screens.

plurals
  1. POI'm having problems using a Singleton to pass an array in Objective-c. (code included)
    text
    copied!<p>So I'm creating an array called fruits which I would like to share between multiple views. This is my code:</p> <pre><code>#import &lt;foundation/Foundation.h&gt; @interface MyManager : NSObject { NSMutableArray *fruits; } @property (nonatomic, retain) NSMutableArray *fruits; + (id)sharedManager; @end #import "MyManager.h" static MyManager *sharedMyManager = nil; @implementation MyManager @synthesize fruits; #pragma mark Singleton Methods + (id)sharedManager { @synchronized(self) { if (sharedMyManager == nil) sharedMyManager = [[self alloc] init]; } return sharedMyManager; } - (id)init { if ((self = [super init])) { fruits = [[NSMutableArray alloc] init]; } return self; } -(void) dealloc{ self.fruits = nil; [super dealloc]; } @end </code></pre> <p>Now I'm using the following code so that I can use workouts in the new view</p> <pre><code>#import "MyManager.h" @interface Chest : UIViewController { IBOutlet MyManager *fruits; } @property (nonatomic, retain) IBOutlet MyManager *fruits; -(IBAction) goToList: (id) sender; @end </code></pre> <p>When a button is clicked, goToList is called, and I populate my array, fruits</p> <pre><code>#import "Chest.h" @implementation Chest @synthesize fruits; -(IBAction) goToList:(id)sender{ MyManager *fruits = [MyManager sharedManager]; NSString *filePath; NSString *fileContents; filePath = [[NSBundle mainBundle] pathForResource:@"chest_strength" ofType:@"csv"]; fileContents = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; fruits = [fileContents componentsSeparatedByString:@"\n"]; } </code></pre> <p>When I output the elements of *fruits in this view, everything works fine. Now when I try to access this same variable in the other view, it says the array is null. Here's the code for the second view:</p> <pre><code>@interface List : UIViewController { IBOutlet MyManager *fruits; } @property (nonatomic, retain) IBOutlet MyManager *fruits; @end #import "List.h" #import "MyManager.h" @implementation List @synthesize fruits NSLog(@"%@", fruits); //This is the part that isn't displaying correctly. I'm getting a null here </code></pre> <p>So my question is, how do I do this so that I can get the array fruits that I populated in Chest and use it in List so that I can display the contents of the array in that view? </p> <p>Thank you to everybody who answers. This problem is seriously bogging me down and I need to finish this project ASAP. Much appreciated.</p>
 

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