So I’m creating an array called fruits which I would like to share between multiple views. This is my code:
#import <foundation/Foundation.h>
@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
Now I’m using the following code so that I can use workouts in the new view
#import "MyManager.h"
@interface Chest : UIViewController {
IBOutlet MyManager *fruits;
}
@property (nonatomic, retain) IBOutlet MyManager *fruits;
-(IBAction) goToList: (id) sender;
@end
When a button is clicked, goToList is called, and I populate my array, fruits
#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"];
}
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:
@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
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?
Thank you to everybody who answers. This problem is seriously bogging me down and I need to finish this project ASAP. Much appreciated.
You’ve changed a few things in this question but the fundamental problem remains: the array is a property of your singleton, and you are not treating it as such.
Whenever you refer to the array, outside of the singleton, do it like this:
If you are accessing it frequently, you can create a local ivar, but you certainly wouldn’t have it as an IBOutlet, which you are doing in your last code sample. How is that ever going to be set?