Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Josh Kahane

macrumors 6502
Original poster
Aug 29, 2006
439
1
Suffolk, UK
Hi

So, it should be simpler than I am making it, perhaps to little sleep on my end. Anyway, I want to quite simply have access to an array across all of my classes.

So for example I have made the array in view1.h and make changes to it in view1.m. However I want to display the array in vew2.m.

See what I mean? Any help would be much appreciated, thanks.
 

robbieduncan

Moderator emeritus
Jul 24, 2002
25,611
893
Harrogate
My recommendation (which is not always agreed with on here, ymmv) is to put it into your data model somewhere. If you want a set of globally accessible variables then you can have them via a few different methods:

If you are only tracking a reasonable number of things (so for your array lets say <1000 items in it) and you want the state of this array and it's contents to survive across program runs then us NSUserDefaults. That's basically what it's there for and as a singleton is available wherever you want it.

If you don't want to use NSUserDefaults then use your own singleton object. This is pretty simple to do:

.h
Code:
@interface MySingleton : NSObject
{
	NSMutableArray *array;
}
//
// Singleton object accessor.  All access to this object should be done via this object.  Do not use [[MySingleton alloc] init];
+ (MySingleton *) sharedSingleton;
@property (retain, nonatomic) array;

.m
Code:
@implementation MySingleton
@synthesize array;
static MySingleton *_sharedMySingleton = nil;
// Factory method.  Basically copied from http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/chapter_3_section_10.html
+ (MySingleton *) sharedSingleton
{
    @synchronized(self)
	{
        if (_sharedMySingleton == nil) 
		{
            [[self alloc] init]; // assignment not done here
            self.array  = [NSMutableArray array];
        }
    }
    return _sharedMySingleton;
}
//
// Allocation method.  Basically copied from http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/chapter_3_section_10.html
+ (id)allocWithZone:(NSZone *)zone
{
    @synchronized(self)
	{
        if (_sharedMySingleton == nil)
		{
            _sharedMySingleton = [super allocWithZone:zone];
            return _sharedMySingleton;  // assignment and return on first allocation
        }
    }
    return nil; //on subsequent allocation attempts return nil
}
//
// Cleans up the instance
- (void) dealloc
{
	self.array = nil;
	[super dealloc];
}
@end

Note this is mostly copy/pasted from code that I actually use. I have made some modifications so I might have messed it up!
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.