开发者

CLISTs in Objective C

I have cpp code where the struct objects are put into the CLISTS. I am porting this code into Objective C.

CLIST is similar to a doubly linked list with .RemoveAt , .GetAt , .InsertBefore , .GetNext , .GetHeadPosition functions.

How to implement the same in Objective C. Do I need to implement doubly linked list in Objective C开发者_StackOverflow社区.Is there any other predefined methods to use it.


A CLIST is presumably circular? Hence the GetHeadPosition?

In any case, NSArray (or, NSMutableArray in this case, since you want to be inserting) is the normal way to keep ordered lists in Objective-C.

For RemoveAt, use removeObjectAtIndex:. For GetAt, use objectAtIndex:. For InsertBefore you're probably going to want to write a little something like:

- (void)insert:(id)objectToInsert before:(id)referenceObject
{
    int index = [array indexOfObject:referenceObject];

    if(index == NSNotFound) return; // or whatever you'd expect. 
                                    // Maybe object is just inserted at the end?

    index = index - 1;
    if(index < 0) index = [array count];
    [array insertObject:objectToInsert atIndex:index];
}

(which would probably go better in an NSArray category, but you get the point)

For GetNext and GetHeadPosition you probably want to keep your array position in a separate variable. So for GetNext:

arrayPosition = (arrayPosition + 1)%[array count];
return [array objectAtIndex:arrayPosition];

And for GetHeadPosition, just:

return arrayPosition;

EDIT: for iterating through an NSArray, the easiest way is actually to ignore anything explicit and just use:

for(ObjectType *object in array)
{
     /* do something with object */
}

That generally means you don't really need an analogue of GetNext, but you can't mutate the array while in that loop so it's not always usable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜