简体   繁体   中英

Access the contents of an NSMutableArray between classes

I have an NSMutableArray in one of my classes. But I need to access the information contained within that array from another class. I have tried using properties, but I eithor did it wrong, or its not working for me. I tried NSUserDefaults but also no luck. I tried using

MainGame *mainGameClass = [[MainGame alloc]init];

NSMutableArray *snacksLocationArray = main.snacksArray;

but none of this seems to work. The two classes are named: MainGame and Kool

Thanks in advance.

If you provide access to your array then anyone should be able to access it. Using a singleton is more like making it a global variable than just allowing access to it.

// In MainGame.h
@interface MainGame : NSOBject {
    NSMutableArray *snacksLocationArray;
}
@property (retain) NSMutableArray *snacksLocationArray;
@end

// In MainGame.m
@implementation MainGame
@synthesize snacksLocationArray;
@end

// In Kool.h
@interface Kool : NSObject {
}
- (void) doSomethingFunkyWithSnacksArray: (NSMutatableArray *) a;
- (void) doSomethingWeirdWithMainGame: (MainGame *) g;
@end

// In Kool.m
@implementation Kool
- (void) doSomethingFunkyWithSnacksArray: (NSMutatableArray *) a {
    [a addObject: @"Funky"];
}
- (void) doSomethingWeirdWithMainGame: (MainGame *) g {
    [self doSomethingFunkyWithSnacksArray: g.snacksLocationArray];
    [g.snacksLocationArray addObject: @"Weird"];
}

Does this do what you are thinking? Lets you access the array from methods in Kool . "Funky" and "Weird" will be properly stored in the array for use within MainGame .

You could also set an ivar to the array within Kool for access to the array using methods that may not have access to the MainGame object.

You could use a singleton, on which you have your mutablearray set as a property. So you could call something like [MainGame sharedGame].snacksArray from anywhere within your app.

Here's what your sharedGame method should look like:

static MainGame *sharedGame = nil;

+ (MainGame *)sharedGame {

    if(sharedGame == nil)
        sharedGame = [[super alloc] init];

    return sharedGame;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM