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!
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.
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?
I think you'll find that it doesn't work in C++ (but they might have changed the grammar rules so that it does). You probably mean something more like this:
struct Node {
event *thing;
Node *next;
};
That works in C++ because Node
is equivalent to struct Node
if there isn't already something called Node
(this sometimes causes puzzling errors when Foo
is both a class and the instance method of another class, which happens in some coding styles).
The fix is to say struct Node
. I prefer this; it seems more pure. There are some good reasons to use a typedef (e.g. things like TUInt64
which might have historically been a struct due to lack of compiler support). If you do use a typedef, there's no reason to give the struct a different name since they're in different namespaces (IIRC structs are a "tag namespace").
The usual typedef version is something like this:
typedef struct Node Node;
struct Node {
event *thing;
Node *next;
};
Alternatively, change the file extension to .mm and then it works because you're compiling Objective-C++!
精彩评论