覆盖包含来自另一个类的对象的类的描述方法

时间:2014-08-08 04:10:15

标签: objective-c class inheritance

当一个类在包含来自另一个类的几个对象时标识自己时,我很困惑。

让我们说:

我有2个Classes和1个subClass:

一个。股票

湾ForeignStock(股票子类)

℃。持股

对于Stock和ForeignStock,我已经覆盖了描述方法,所以当我将它们的对象放入一个数组时,那些2可以描述自己,并且数组的NSLogged内容。

库存类别说明

-(NSString *)description{

    NSString *objectDescriptionFormat = @"\n" "========= Properties of Stock Value %@ ==========\n"
    "Purchase price is %f\n" "Current Price is %f\n" "Number of Shares bought is %i\n" "\n"
    "------------------- Total Value & Cost ------------------\n"
    "Value in dollar for this stock is %f\n" "Cost in dollar for this stock is %f\n" "\n";

    return [NSString stringWithFormat:objectDescriptionFormat, 
    [super description],self.purchaseSharePrice,self.currentSharePrice,
    self.numberOfShares,
    self.valueInDollars,self.costInDollars];
}

ForeignStock Class的描述

 -(NSString *)description
 {
     NSString *objectDescriptionFormat = @"%@" "Conversion rate for this stock is %f\n"  "\n" ;

     return [NSString stringWithFormat: objectDescriptionFormat,[super description],self.conversionRate];
 }

我把从Stock& amp; ForeignStock类在StockHolding的一个实例中,但是这里有一些问题:

  1. 如何在StockHolding中显示对象? (我把数组作为StockHolding的属性)

  2. 我是否必须在StockHolding中创建2方法才能从Stock&amp ;;外国股票类?或者1个addObject方法就够了吗?

  3. 从上面的描述方法中可以看出,Stock& ForeignStock有不同的价值观 如何设置calculateValue来计算StockHolding中存储的每个库存值?

  4. 注意:我创建了自定义访问者

    @interface Portfolio : NSObject
    {
        NSMutableArray  *_portfolioStocks;
    }
    @property (nonatomic, copy)NSArray *portfolioStocks;
    
    -(NSArray *)portfolioStocks{
        return  [_portfolioStocks copy];
    }
    
    -(void)setPortfolioStocks:(NSArray *)portfolioStocks{
    
        _portfolioStocks = [portfolioStocks mutableCopy];
    }
    
    - (void)addStocks: (StockHolding *) newStocks{
    
        // is portfolio array nil?
        if (!_portfolioStocks) {
            //create array
            _portfolioStocks = [NSMutableArray new];
        }
        [_portfolioStocks addObject:newStocks];
    }
    

0 个答案:

没有答案