ObjC:NSLog指针名称

时间:2012-12-13 05:53:27

标签: objective-c class pointers instance nslog

我在NSMutableArray中填充了我创建的3个类实例。现在我想迭代这个数组来获得一些变量值。我能够这样做,但无法打印我的实例名称(面包,水,......)而是我得到了他们的地址。 我想这很简单,但我有点挣扎,所以如果有人知道如何...... 谢谢

#import <Foundation/Foundation.h>
#import "StockHolding.h";

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

StockHolding *bread = [[StockHolding alloc] init];
[bread setPurchaseSharePrice:100];
[bread setCurrentSharePrice:120];
[bread setNumberOfShares:100];

StockHolding *water = [[StockHolding alloc] init];
[water setPurchaseSharePrice:100];
[water setCurrentSharePrice:80];
[water setNumberOfShares:10];

StockHolding *tomatoes = [[StockHolding alloc] init];
[tomatoes setPurchaseSharePrice:100];
[tomatoes setCurrentSharePrice:50];
[tomatoes setNumberOfShares:1];

NSMutableArray *myStock = [NSMutableArray arrayWithObjects:bread, water, tomatoes, nil];

for (StockHolding *s in myStock)
{
    NSLog(@"Here is what I paid for my %p : %f", s, [s costInDollars]);
    NSLog(@"Here is what I earn for my %p : %f", s, [s valueInDollars]);

}

[pool drain];
return 0;

}

2 个答案:

答案 0 :(得分:1)

为什么不在StockHolding类上实现-(NSString *)description方法?然后你可以在字符串格式中使用%@,它会在那里输出描述。

或者,您也可以使用%@输出StockHolding实例的任何其他字符串属性。

答案 1 :(得分:0)

如果您想要NSLog一个对象及其指针名称,您可以在预处理器宏#define OLog(x) NSLog(@"%s = %@",#x, x);中添加此#define