我正在阅读 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;
}