user1626775
user1626775

Reputation: 9

How do I print array of objects? Objective C

I have the class Stockholging where its created the properties and methods costInDollars & valueInDollars.. I need to create a instance of each stock add each object to the array and then print it useing fast enumeration.

//Instantiation and creation of each stock

    StockHolding *o1 = [[StockHolding alloc]init];
    StockHolding *o2 = [[StockHolding alloc]init];
    StockHolding *o3 = [[StockHolding alloc]init];

//Setting the values, and calling the methods costInDollars and valueInDollars for each object

    [o1 setPurchaseSharePrice:2.30];
    [o1 setCurrentSharePrice:4.50];
    [o1 setNumberOfShares:40];
    [o1 costInDollars];
    [o1 valueInDollars];

    [o2 setPurchaseSharePrice:12.10];
    [o2 setCurrentSharePrice:10.58];
    [o2 setNumberOfShares:30];
    [o2 costInDollars];
    [o2 valueInDollars];

    [o3 setPurchaseSharePrice:45.10];
    [o3 setCurrentSharePrice:49.51];
    [o3 setNumberOfShares:210];
    [o3 costInDollars];
    [o3 valueInDollars];

// Creation an array and adding objects to the array

    NSMutableArray *bolsa = [[NSMutableArray alloc]init];
    [bolsa addObject:o1];
    [bolsa addObject:o2];
    [bolsa addObject:o3];

Upvotes: 0

Views: 1014

Answers (2)

FuzzyBunnySlippers
FuzzyBunnySlippers

Reputation: 3397

In your class, you need to provide a method for the description selector. This will return an NSString* of the contents of your class, formatted as you wish.

For example:

-(NSString*)description
{
   NSString* str1 = [NSString stringWithFormat:@"Purchase Share Price = %f",currentSharePrice];
   NSString* str2 = [NSString stringWithFormat:@"Current Share Price = %f",currentSharePrice];
   ... // do the rest of the items
   NSArray* strings =[NSArray arrayWithObjects:str1,str2,<the rest of them>, nil]
   NSString* result = [strings componentsJoinedByString:@"\n"];
   return result;
}

And then:

NSLog("%@",bolsa);

NOTE: This is a good approach whenever you need to debug/log objects in objective-c...having a method to convert complex objects into simple representations (i.e. a string) can be really helpful. Coding skill is not just knowing about functions and templates...its also about techniques and tools.

Upvotes: 2

Grzegorz Krukowski
Grzegorz Krukowski

Reputation: 19802

In your StockHolding class implement that method:

- (NSString*) description

Than use:

NSLog(@"%@", bolsa);

It will iterate through array and print string taken from above method for each object inside this array.

Upvotes: 1

Related Questions