Search code examples
iosobjective-ckvc

Collection operators valueForKeyPath returns nil


Below is sample code which I am using to test collection operators:

NSMutableSet *set ;

sampleClass *obj1 = [[sampleClass alloc]init];

sampleClass *obj2 = [[sampleClass alloc]init];
sampleClass *obj3 = [[sampleClass alloc]init];
sampleClass *obj4 = [[sampleClass alloc]init];
sampleClass *obj5 = [[sampleClass alloc]init];


obj1.age = 30 ;
obj2.age = 30 ;
obj3.age = 30 ;
obj4.age = 30 ;
obj5.age = 30 ;


[set addObject:obj1];
[set addObject:obj2];
[set addObject:obj3];
[set addObject:obj4];
[set addObject:obj5];

NSNumber *transactionAverage = [set valueForKeyPath:@"@sum.age"];

transactionAverage is always returning me nil. Looks like small mistake from my side, but not able to identify that.


Solution

  • It's because you don't allocate the NSMutableSet object with:

    NSMutableSet *set = [[NSMutableSet alloc] init];
    

    Therefore everything you do on the set is silently ignored.