views:

352

answers:

4

please give me some examples.thanks a lot

A: 

you can find some examples in this blog article: Singletons, AppDelegates and top-level data

mouviciel
+1  A: 

In Cocoa, the typical collection container for an ordered list in an NSArray.

To make a global array variable, add this to a header file:

extern NSMutableArray *myGlobalArray;

That means, there exists a variable named myGlobalArray, and it refers to an instance of NSMutableArray.

Add this to an implementation file:

NSMutableArray *myGlobalArray = nil;

That actually makes a variable myGlobalArray that points to an instance of NSMutableArray rather than just declaring that one exists.

Now, in any other file where you want to use myGlobalArray, just import the header file (the declaration that the variable exists).

All of that said, this is usually not a good approach to take since it offers zero encapsulation. Instead if you really want global data, you might try something like this.

In a header:

extern NSArray *AllItems(void);
extern void AddItem(MyItem *item);
extern void RemoveItem(MyItem *item);
extern void SetAllItems(NSArray *items);

In a .m file:

static NSMutableArray *items = nil;

static NSMutableArray *items(void) {
    if (!items) {
        items = [[NSMutableArray alloc] init];
    }
    return items;
}

NSArray *AllItems(void) {
    return items();
}

void AddItem(MyItem *item) {
    [items() addObject:item];
}

void RemoveItem(MyItem *item) {
    [items() removeObject:item];
}

void SetAllItems(NSArray *value) {
    if (items != value) {
        [items release];
        items = [value mutableCopy];
    }
}
Jon Hess
-1, an array is not a linked list. Also, your implementation isn't thread safe.
Georg
+1  A: 

The CHDataStructures framework provides a few linked list implementation (singly linked, doubly linked, doubly-linked sets). But honestly, it's not that difficult to build one yourself...

Dave DeLong
A: 

Just like in C.

swegi