尝试创建总价值在Objective-C中的股票投资组合,但不确定该方法 [英] Trying to create a portfolio of stocks with a total value in Objective-C, but unsure of the approach

查看:69
本文介绍了尝试创建总价值在Objective-C中的股票投资组合,但不确定该方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Big Nerd Ranch指南(第2版)自学Objective-C,直到第21章,我都没有遇到任何问题.我检查了该书的论坛,但这没有帮助,因为那里的大多数人是具有意大利面条代码的新手,我也不想养成不良习惯...我也是一个初学者,因为这是我的第一门主要语言,但是您看到意大利面条的代码就很明显.

I'm currently teaching myself Objective-C with the Big Nerd Ranch guide (2nd edition) and I have not had a problem up until chapter 21. I checked the book's forum, but it was of no help because most people there are newbies with spaghetti code, and I do not want to adopt bad habits...I am a beginner too, as this is my first major language, but spaghetti code is obvious when you see it.

我必须从上一章中获得代码,并创建一个工具来创建BNRPortfolio类的实例,并用持股量填充该类(还必须对投资组合的当前值求和).然后,我必须向BNRStockHolding添加一个符号属性,该属性将股票行情代码以NSString的形式保存.

I have to take my code from a previous chapter and make a tool that creates an instance of a BNRPortfolio class and fills it with stock holdings (must also sum up the portfolio's current value). Then I have to add a symbol property to BNRStockHolding that holds the stock ticker symbol as an NSString.

我对于在何处添加代码以及如何开始感到完全困惑.在我的在线研究中,这一章的写作不佳,并且是大多数读者所困扰的地方……作者们甚至同意,在以后的版本中(如果由于Swift的介入而改写),他们将重新编写整章.

I am just completely confused as to where to add the code to do this and how to begin. From my research online, this chapter was poorly written and is where most readers have gotten stuck...the authors even agreed that in future editions (if ever because of Swift moving in) they would re-write the entire chapter.

目前,我上一章的代码如下:

Currently, my code from a previous chapter looks like this:

BNRStockHolding.h

#import <Foundation/Foundation.h>

@interface BNRStockHolding : NSObject

@property (nonatomic) float purchaseSharePrice;
@property (nonatomic) float currentSharePrice;
@property (nonatomic) int numberOfShares;

- (float)costInDollars;
- (float)valueInDollars;

@end

BNRStockholding.m

#import "BNRStockHolding.h"

@implementation BNRStockHolding

- (float)costInDollars
{
    return _purchaseSharePrice * _numberOfShares;
}

- (float)valueInDollars
{
    return _currentSharePrice * _numberOfShares;
}

@end

接下来,我必须添加转换率将价值和成本转换为美元的外国股票:

Next, I had to add foreign stocks with a conversion rate that converted the values and cost into U.S. dollars:

BNRForeignStockHolding.h

#import <Foundation/Foundation.h>
#import "BNRStockHolding.h"

@interface BNRForeignStockHolding : BNRStockHolding

@property (nonatomic) float conversionRate;

@end

BNRForeignStockHolding.m

#import "BNRForeignStockHolding.h"

@implementation BNRForeignStockHolding : BNRStockHolding

- (float)costInDollars
{
    float foreignCostInDollars = super.costInDollars;
    return _foreignCostInDollars * _conversionRate;
}
- (float)valueInDollars
{
    float foreignValueInDollars = super.valueInDollars;
    return _foreignValueInDollars * _conversionRate;
}

@end

我的主文件: main.m

#import <Foundation/Foundation.h>
#import "BNRForeignStockHolding.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        BNRStockHolding *stock0 = [[BNRStockHolding alloc]init];
        BNRStockHolding *stock1 = [[BNRStockHolding alloc]init];
        BNRStockHolding *stock2 = [[BNRStockHolding alloc]init];
        BNRForeignStockHolding *stock3 = [[BNRForeignStockHolding alloc]init];

        stock0.purchaseSharePrice=2.30;
        stock0.currentSharePrice=4.50;
        stock0.numberOfShares=40;

        stock1.purchaseSharePrice=12.19;
        stock1.currentSharePrice=10.56;
        stock1.numberOfShares=90;

        stock2.purchaseSharePrice=45.10;
        stock2.currentSharePrice=49.51;
        stock2.numberOfShares=210;

        stock3.purchaseSharePrice=43.05;
        stock3.currentSharePrice=28.31;
        stock3.numberOfShares=15;
        stock3.conversionRate=0.3;

        NSMutableArray *stocks = [NSMutableArray arrayWithObjects:stock0, stock1, stock2, stock3, nil];
        for (BNRForeignStockHolding *s in stocks) {
            float a = s.purchaseSharePrice;
            float b = s.currentSharePrice;
            int c = s.numberOfShares;

             if ([s isMemberOfClass:[BNRForeignStockHolding class]]) {

                float d = s.foreignCostInDollars;
                float e = s.foreignValueInDollars;
                NSLog(@"\n Purchase Price: %.2f\n Current Price: %.2f\n Number of Shares %d\n Cost in Dollars %f\n Value in Dollars %f\n", a, b, c, d, e);
            }
            else {

                float d = s.costInDollars;
                float e = s.valueInDollars;
                NSLog(@"\n Purchase Price: %.2f\n Current Price: %.2f\n Number of Shares %d\n Cost in Dollars %f\n Value in Dollars %f\n", a, b, c, d, e);
            }

            }
    }
    return 0;
}

我尝试过:

在BNRStockHolding.h中,我创建了一个实例变量:

In BNRStockHolding.h, I created an instance variable:

- (float)currentTotalValue

在BNRStockHolding.m中,我是这样实现的:

and in BNRStockHolding.m, I implemented it like this:

-(float)currentTotalValue
{
return _currentTotalValue = _currentSharePrice * _numberOfShares;
}

然后在main.m中,将其添加到股票数组的'for'函数中:

Then in main.m, I added this to the 'for' function in my stocks array:

float f = s.currentTotalValue;

然后将%.2f @,f添加到我的NSLog打印输出中.

Then added %.2f@, f to my NSLog print out.

除了此警告以外,它运行得很好:

It worked perfectly except for this caveat:

它只是给了我每只股票的价值,而没有转换外国股票.我有点理解为什么,但是本章没有彻底解释如何解决这样的问题,所以我完全迷失了.我什至无法尝试添加股票代码,因为我不确定该在哪里实现.

It simply gave me the value of each individual stock without converting the foreign stocks. I somewhat understand why, but the chapter did not explain thoroughly how to attack such a problem, so I am totally lost. I couldn't even attempt adding the stock ticker symbol because I wasn't sure where to implement it.

当手动将我的投资组合的总价值加在一起时,包括转换后的外国价值,总价值应为$ 17,774.895.请记住,这些库存是假装的,转换率也是假装的.

When adding up the total value of my portfolio by hand, converted foreign values included, the total should be $17,774.895. Keep in mind that these stocks are pretend, as is the conversion rate, etc.

谢谢您的帮助,我们将不胜感激!

Thank You for any help, it is greatly appreciated!

编辑添加

问题解决了,我不得不用costInDollars和valueInDollars的重写重写BNRStock和BNRForeign .h和.m文件,并为NSLog添加异常,以通过[NSString stringWithFormat:]方法为每个输出单独的结果.然后,我添加了建议的汇总代码,并进行了一些调整,一切正常.我还通过在.h和.m文件中将符号定义为指针,然后将它们包含在[NSString stringWithFormat:]打印输出命令中,毫无问题地添加了股票行情自动收录器.

Problem solved, I had to rewrite my BNRStock and BNRForeign .h and .m files with overrides for costInDollars and valueInDollars, as well as add an exception for NSLog to print out separate results for each via an [NSString stringWithFormat:] method. Then I added the sum code recommended with a few tweaks and everything worked well. I also added the stock tickers with no problem by defining symbol as a pointer in my .h and .m files and then including them in the [NSString stringWithFormat:] printout command.

向danH大喊,因为注意到我的costInDollars和valueInDollars应该已被覆盖以同时适用于BNRStock和BNRForeign类,因为这是我程序的主要问题.

Shoutout to danH for noticing that my costInDollars and valueInDollars should have been overridden to work for both BNRStock and BNRForeign classes, as that was the main issue with my program.

推荐答案

不熟悉这本书,但听起来像BNRPortfolio是一个新类,应使用新的.h和.m文件.您应该根据到目前为止已完成的工作来命名约定.开始看起来像这样:

Not familiar with the book, but it sounds like BNRPortfolio is a new class, deserving of a new .h and .m file. You should crib naming conventions from the work you've done so far. A start would look something like this:

// in BNRPortfolio.h

@class BNRStockHolding;

@interface BNRPortfolio : NSObject

- (void)addHolding:(BNRStockHolding *)holding;
- (float)portfolioValue;

@end

// in BNRPortfolio.m

#import "BNRPortfolio.h"
#import "BNRStockHolding.h"

@interface BNRPortfolio ()  // fixed typo here
@property (strong, nonatomic) NSMutableArray holdings;
@end

@implementation BNRPortfolio

- (id)init {
    self = [super init];
    if (self) {
        _holdings = [NSMutableArray array];
    }
    return self;
}

- (void)addHolding:(BNRStockHolding *)holding {
    [self.holdings addObject:holding];
}

- (float)portfolioValue {
    float sum = 0;
    for (BNRStockHolding *holding in self.holdings) {
        sum += [holding valueInDollars];
    }
    return sum;
}

@end

您应该能够对其中之一进行分配-初始化,然后添加外国和国内的几处股份,然后索要投资组合的价值.

You should be able to alloc-init one of these, then add several holdings, foreign and domestic, and then ask for the portfolio value.

编辑-通过主方式调用它:

EDIT - call it from main this way:

#import <Foundation/Foundation.h>
#import "BNRStockHolding.h"
#import "BNRForeignStockHolding.h"
#import "BNRPortfolio.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {

    // build stock0, stock1, stock2, stock3 just as you have them, then...

    BNRPortfolio *portfolio = [[BNRPortfolio alloc] init];

    [portfolio addHolding:stock0];
    [portfolio addHolding:stock1];
    [portfolio addHolding:stock2];
    [portfolio addHolding:stock3];

    NSLog(@"The total value of the portfolio in USD is %f", [portfolio portfolioValue]);
    }
return 0;

}

这篇关于尝试创建总价值在Objective-C中的股票投资组合,但不确定该方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆