0

我正在阅读 Apple 的 Key Value Programming Guide。在主题简单集合运算符中,我读到:

以下示例返回交易中对象的交易金额平均值: NSNumber *transactionAverage=[transactions valueForKeyPath:"@avg.amount"];

我尝试编写一个可以使用上述内容的程序。以下是该程序的文件。我无法理解为什么上述内容对我不起作用。

事务.h

    #import <Foundation/Foundation.h>

@interface Transaction : NSObject
{
NSString *payee;
NSNumber *amount;
NSDate *date;
}
- (void) setPayee: (NSString *) aP 
    setAmount: (NSNumber *) aN
      setDate: (NSDate *) aD;

@end

Transaction.m #import "Transaction.h"

@implementation Transaction
- (void) setPayee: (NSString *) aP 
    setAmount: (NSNumber *) aN
      setDate: (NSDate *) aD 
{
payee = aP;
amount = aN;
date = aD;
} 
@end

事务数据库.h

#import <Foundation/Foundation.h>
#import "Transaction.h"
@interface TransactionDataBase : NSObject
{
NSMutableArray *tArray;
}
  - (id) objectInTArrayAtIndex: (NSUInteger) index;
- (void) insertObject: (Transaction *) tA
inTArrayAtIndex: (NSUInteger) index;
  - (NSUInteger) countOfTArray;
  @end

事务数据库.m

     #import "TransactionDataBase.h"

   @implementation TransactionDataBase
  - (id) init
  {
self = [super init];
if (self) {
    tArray = [[NSMutableArray alloc] initWithCapacity:40];
   }
    return self;
  }

    - (id) objectInTArrayAtIndex: (NSUInteger) index
  {
  return [tArray objectAtIndex:index];
  }

  - (void) insertObject: (Transaction *) tA
    inTArrayAtIndex: (NSUInteger) index
 {
[tArray insertObject:tA atIndex:index];
   }

 - (NSUInteger) countOfTArray
  {
return [tArray count];
    }
   @end


  main.m:


  #import <Foundation/Foundation.h>
    #import "Transaction.h"
   #import "TransactionDataBase.h"

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

      @autoreleasepool {

    Transaction *t1 = [[Transaction alloc] init];
    Transaction *t2 = [[Transaction alloc] init];
    Transaction *t3 = [[Transaction alloc] init];

    NSDate *nowDate = [[NSDate alloc]  initWithString:@"2.4.2012"];
    NSDate *nowDate2 = [[NSDate alloc] initWithString:@"2.4.2012"];
    [t1 setPayee:@"c" setAmount:[NSNumber numberWithInt:3000] setDate:nowDate];

    [t2 setPayee:@"c" setAmount:[NSNumber numberWithInt:5000] setDate:nowDate2];


    [t3 setPayee:@"y" setAmount:[NSNumber numberWithInt:1000] setDate:nowDate2];

    TransactionDataBase *db1 = [[TransactionDataBase alloc] init];
    [db1 insertObject:t1 inTArrayAtIndex:0];
    [db1 insertObject:t2 inTArrayAtIndex:1];
    [db1 insertObject:t3 inTArrayAtIndex:2];
    NSNumber *avgT = [db1 valueForKeyPath: "@avg.amount"];
    NSLog(@"%@", avgT);


}
return 0;
  }
4

2 回答 2

0

您的TransactionDataBase类必须支持一个键路径,该路径返回一个包含其存储值的数组。此外,Transaction该类必须支持 key 的键值编码@"amount"。您必须为这些类添加适当的属性。

然后,您使用的键路径[db1 valueForKeyPath: "t1.@avg.amount"]必须考虑这些属性的名称,即使用您当前的代码,TransactionDataBase必须可以通过键访问项目数组@"t1"

于 2012-04-20T15:49:29.663 回答
0

我想你想要 NSNumber *avgT = [db1 valueForKeyPath:@"@avg.amount"]; 您想要对数组中的所有“数量”值进行平均,而不仅仅是在 t1 对象中——对一个值进行平均是没有意义的。

于 2012-04-20T15:51:25.417 回答