Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Linked Lists in Objective C

typedef struct {
    NSString *activty;
    NSString *place;
    float latitude;
    float longitude;
} event;

typedef struct {
    event *thing;
    Node *next;
} Node;

This is the code I have in my .h file to create two structs to hold data (one for an events name/place/location, and one for the nodes of a linked list. I can use the event struct in the node struct, but I need to use the node struct within itself. In C++ this would work, but how can I achieve this in objective-c? Thank you!

like image 271
Inanepenguin Avatar asked Nov 23 '10 23:11

Inanepenguin


2 Answers

Why bother with a struct? Just use a class:

@interface MyEvent:NSObject
@property(copy) NSString *activity;
@property float latitude;
... etc ...
// and that linked list gunk
@property(retain) MyEvent *nextEvent;
@end

@implementation MyEvent
@synthesize activity, latitude, nextEvent;

- (void) dealloc
{
    [activity release], activity = nil;
    [nextEvent release], nextEvent = nil;
    [super dealloc];
}
@end

There is no significant overhead vs. a structure (if the method calls are really measurable, you could even expose ivars directly). Better yet, the moment you want to archive the struct, add business logic, or do anything else interesting, you can simply add methods.

like image 105
bbum Avatar answered Oct 23 '22 06:10

bbum


You need to name your structure like you would in C. For example:

typedef struct Node {
    event *thing;
    struct Node *next;
} Node;

A better question, though, is why do you want to make this linked list in the first place? Why not use one of the container types provided by the framework?

like image 27
Carl Norum Avatar answered Oct 23 '22 07:10

Carl Norum