This code works fine, but each time i look at it, i die a little bit inside. 🙁
Can you help me streamline it a bit?
Is there a more elegant way to .append(SomeString)? (To give you some perspective, code prints elements of the Linked List)
- (NSString *) description {
Node* tempNode = [self firstNode];
if (tempNode == nil) {
return @"List contains no elements";
}
NSString *desc= [[NSString alloc] initWithString:@"(null) -- "];
desc = [desc stringByAppendingString:[firstNode nodeCharacter]];
desc = [desc stringByAppendingString:@" -- "];
while ([tempNode nextNode] != nil) {
desc = [desc stringByAppendingString:[[tempNode nextNode]nodeCharacter]];
desc = [desc stringByAppendingString:@" -- "];
tempNode = [tempNode nextNode];
}
return [desc stringByAppendingString:@" (null)"];
}
First of all, if you want to build a string step by step or modify it, stop using
stringByAppendingString:, and useNSMutableStringinstead ofNSString!!!Then, for your matter, you can even use
stringWithFormat:to build part of your string.Finally, you forgot to manage your memory: you alloc/init your string but never release it (and as your reassign the
descvariable the line after, you loose track of the allocated memory and have a leak.So here is the revised code:
(Note that you may also build an NSArray of the nodes of your list and use
componentsJoinedByStringthen at the end… so you have multiple possibilities here anyway)