【问题标题】:method that sorts an NSMutableArray of custom objects then returns an NSArray对自定义对象的 NSMutableArray 进行排序然后返回 NSArray 的方法
【发布时间】:2014-05-01 08:48:51
【问题描述】:

我正在学习 Objective-C,这是我的第一篇文章,请保持温和。我已经搜索了该网站并重新阅读了我的学习资料,但不确定我不理解/做对了什么。 我的目标是向现有类添加一个方法,该方法返回数组中最有价值的三个“股票”的 NSArray。我有一个有效的“股票”类,带有一个“valueInDollars”方法,以及一个可以保存我的股票类实例的“投资组合”类。我正在使用 NSSortDescriptor 对我的 NSMutableArray 股票按其 valueInDollars 进行排序,然后返回具有前三个值的可变数组的副本。这是我的 BNRStockHolding.h 文件:

#import <Foundation/Foundation.h>
    @class BNRPortfolio;

    @interface BNRStockHolding : NSObject

   {
        // declare instance variables
        float _purchaseSharePrice;
        float _currentSharePrice;
        int _numberOfShares;
        // add an instance variable that will allow us to print out the solution with less code
        NSString *_stockName;

    }
    // create a holder to use in the sorting method of BNRPortfolio
    @property (nonatomic, weak) BNRPortfolio *holder;

    // accesor methods declared
    - (float)purchaseSharePrice;
    - (void)setPurchaseSharePrice:(float)p;
    - (float)currentSharePrice;
    - (void)setCurrentSharePrice:(float)c;
    - (int)numberOfShares;
    - (void)setNumberOfShares:(int)n;
    - (NSString *)stockName;
    - (void)setStockName:(NSString *)s;
    - (void)addYourselfToArray:(NSMutableArray *)theArray;

    // instance methods below are defined in .m file as they are the result of
    // a mathematical equation using the instance variables above
    - (float)costInDollars;
    - (float)valueInDollars;

    @end

还有我的 BNRPortfolio.h 文件:

#import <Foundation/Foundation.h>
    // use @class so we can declare that this portfolio class will access the
    // 'valueInDollars' instance variable from the BNRStockHolding class
    @class BNRStockHolding;

    @interface BNRPortfolio : NSObject

    @property (nonatomic, copy) NSArray *holdings;
    @property (nonatomic, copy) NSArray *mostValuableHoldings;

    - (float)totalValue;
    - (void)addHolding:(BNRStockHolding *)h;
    - (void)removeHolding:(BNRStockHolding *)r;

    @end

和 BNRPortfolio.m 文件:

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

    @interface BNRPortfolio ()

    {
        NSMutableArray *_holdings;
        NSMutableArray *_mostValuableHoldings;
    }

    @end

    @implementation BNRPortfolio

    - (void)setHoldings:(NSArray *)s
    {
        _holdings = [s mutableCopy];
    }

    - (NSArray *)holdings
    {
        return [_holdings copy];
    }

    - (void)setMostValuableHoldings:(NSArray *)m
    {
        _mostValuableHoldings = [m mutableCopy];
    }

    - (NSArray *)mostValuableStocks;
    {
        NSSortDescriptor *highToLow = [NSSortDescriptor sortDescriptorWithKey:@"holder.valueInDollars" ascending:NO];
        [_holdings sortUsingDescriptors: @[highToLow]];
        for (int i = 0; i < 3; i++) {
            for (BNRStockHolding *m in _holdings) {
                [_mostValuableHoldings addObject:m];
                break;
             }
        }
        return [_mostValuableHoldings copy];
    }

    - (void)addHolding:(BNRStockHolding *)h
    {
        // is the holdings array nil?
        if (!_holdings) {
            // create the array
            _holdings = [[NSMutableArray alloc] init];
        }
        // add the holding in to the holdings array
        [_holdings addObject:h];
    }

    // describe how removeHolding works
    - (void)removeHolding:(BNRStockHolding *)r
    {
        if (r) {
            [_holdings removeObject:r];
        }
    }

    - (float)totalValue
    {
        // add the currentValue values of all holdings in the holdings array by iterating through
        // it and returning the sum
        float sum = 0;
        for (BNRStockHolding *h in _holdings) {
            sum += [h valueInDollars];
        }
        return sum;
    }

    // change the description property to return an NSString with the total value of the portfolio
    - (NSString *)description
    {
        return [NSString stringWithFormat:@"<stock portfolio with a total value of %.2f>", self.totalValue];
    }


    @end

你们中的一些人可能会认出类的名称,因为我正在遵循关于 Objective-C 的 Big Nerd Ranch 指南,并且我没有重命名我的类。我已经在专门的 BNR 论坛中搜索了解决方案并将我的问题发布在那里但无济于事,并且书中没有给出解决方案。我非常想学习和理解为什么这不起作用,所以请详细说明你的答案。提前非常感谢您!

【问题讨论】:

    标签: objective-c


    【解决方案1】:

    mostValuableStocks 方法的第一行应该是

    _mostValuableHoldings = [[NSMutableArray alloc] init];
    

    也就是说,我没有看到任何分配/初始化该数组的代码。

    【讨论】:

    • 首先,谢谢大家-@Avt @hypercrypt 和@user3386109-您的回答。我发现在我的方法的- (NSArray *)mostValuableHoldings; 部分中更改代码以包含 NSMutableArray 的简单 alloc/init 就可以了。但是,由于迭代过程中的错误,我得到了一组相同的三只股票,所以我也进行了更改。
    【解决方案2】:

    尝试改变

    NSSortDescriptor *highToLow = 
    [NSSortDescriptor sortDescriptorWithKey:@"holder.valueInDollars" ascending:NO];
    

    NSSortDescriptor *highToLow = 
    [NSSortDescriptor sortDescriptorWithKey:@"valueInDollars" ascending:NO];
    

    NSSortDescriptor *highToLow = 
    [NSSortDescriptor sortDescriptorWithKey:@"SELF.valueInDollars" ascending:NO];
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

      - (NSArray *)mostValuableStocks
      {
          return [[array sortedArrayUsingComparator:^(BNRStockHolding *h1, BNRStockHolding *h2) {
              return [@([h1 valueInDollars]) compare:@([h2 valueInDollars])];
          }] subarrayWithRange:(NSRange){0, 3}];
      }
      

      【讨论】:

        【解决方案4】:

        为了帮助那些有同样问题的人,这里是我为修复BNRPortfolio.m 文件中的问题而更改的部分:

        - (NSArray *)mostValuableHoldings;
        {
        if (!_mostValuableHoldings) {
            _mostValuableHoldings = [[NSMutableArray alloc] init];
        }
        NSSortDescriptor *highToLow = [NSSortDescriptor sortDescriptorWithKey:@"valueInDollars" ascending:NO];
        [_holdings sortUsingDescriptors: @[highToLow]];
            for (int i = 0; i < 3; i++) {
                [_mostValuableHoldings addObject:_holdings[i]];
            }
        return [_mostValuableHoldings copy];
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-10-22
          • 2012-02-12
          • 1970-01-01
          • 1970-01-01
          • 2011-08-30
          • 2011-02-20
          • 1970-01-01
          相关资源
          最近更新 更多