Reputation: 58
I have an array of items, each with their own unique descriptions. Basically, I want to create a method which takes each item from the array and returns a single descriptive string which shows the description of each item in said array.
- (NSString *) itemList
{
NSString *list = [[NSString alloc] init];
for (Item *i in _items)
{
/**
Unsure :S
*/
[NSString stringWithFormat:@"%@: %@.\n", [i firstId], [i name]];
}
return list;
}
Basically, this is the coded logic that I have so far.
Assume I have two items which are initialised as such:
Item *testItem1 = [[Item alloc] initWithIdentifiers:@[@"shovel", @"spade"] name:@"a shovel" andDesc:@"This is a mighty fine shovel"];
Item *testItem2 = [[Item alloc] initWithIdentifiers:@[@"gem", @"crystal"] name:@"a gem" andDesc:@"This is a shiny gem"];
I then add those items to my Inventory object:
[testInventory put:testItem1];
[testInventory put:testItem2];
By calling the Inventory method itemList
[testInventory itemList];
on my inventory (code listed above), I want the following result:
@"shovel: a shovel.\ngem a gem."
Does anyone have any suggestions or pointers. I'm sure it's simple; it's just that I've only recently picked up Obj - C :)
Thanks
Upvotes: 0
Views: 234
Reputation: 1369
I like adding the collection of strings to a mutable array and then calling componentsJoinedByString. It works even more cleanly if it is the description method you want on each object because you don't have to do the collecting loop first.
Create nsmutablearray
For each item in list
Nsmutablearray add object item.property
Return nsmutablearray componentsJoinedByString @", "
If you want the item's description though, you can just do, assuming you have an array with the objects already
TheArray componentsJoinedByString @", "
Upvotes: 0
Reputation: 4254
You can do it more elegantly by overriding the description method for your Item class like this:
- (NSString *) description {
return [NSString stringWithFormat:"%@: %@.", [self firstId], [self name]];
}
and then to generate the string for all the items in the array:
NSString* itemsString = [itemList componentsJoinedByString:@"\n"];
Upvotes: 1
Reputation: 1401
You can just use:
list = [list stringByAppendingFormat:@"%@: %@\n", [i firstId], [i name]];
or try NSMutableString:
NSMutableString *list = [[NSMutableString alloc] init];
[list appendFormat:@"%@: %@\n", [i firstId], [i name]];
Upvotes: 1