如何打印对象数组?目标C.



我有Stockholging类,它在其中创建了属性和方法costInDollar和valueInDollar。我需要创建每个股票的实例,将每个对象添加到数组中,然后使用快速枚举打印它。

实例化和创建每个股票

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

设置值,并为每个对象调用方法成本美元和价值美元

    [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];

创建数组并向数组添加对象

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

在您的类中,您需要为描述选择器提供一个方法。 这将返回类内容的 NSString*,并根据需要进行格式化。

例如:

-(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;
}

然后:

NSLog("%@",bolsa);

注意:当您需要在 objective-c 中调试/记录对象时,这是一个很好的方法。拥有将复杂对象转换为简单表示(即字符串)的方法可能非常有帮助。 编码技能不仅仅是了解函数和模板......它还与技术和工具有关。

在你的 StockHolding 类中实现该方法:

- (NSString*) description

比使用:

NSLog(@"%@", bolsa);

它将循环访问数组并打印从上述方法获取的字符串,用于此数组中的每个对象。

最新更新