0

我在 myMutableArray 中添加了一些数据:

- (void)calculate {

    DataObject* pObj = [DataObject objStart:(dataStart) 
                                     objEnd:(dataEnd) 
                                     objDay:(day)];

    [self.myMutableArray addObject:pObj];
}

我只需要提取 day (int) 并对所有值求和。我在想这样的事情,但我想念如何只提取一天......

  for(id *tObj in self.myMutableArray) {
    // day = day + day
 }

DataObject 在这里实现:

   @implementation DataObject

+ (id)objStart:(NSDate*)objStart objEnd:(NSDate*)objEnd objDay:(int)objDay {

DataObject *dataObject = [[self alloc] init];
dataObject.objStart = objStart;
dataObject.objEnd = objEnd;
dataObject.objDay = objDay;
return dataObject;
}
@end
4

2 回答 2

1

你想要这个吗 ?(我必须做出很多自我假设)

NSUInteger totalDay;
for(id tObj in self.myMutableArray) {
    // day = day + day
  totalDay+=tObj.objDay;
}
于 2012-11-27T14:41:12.823 回答
1

可可通过键值编码提供了一种优雅且非常好的解决方案。您可以查看http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/KeyValueCoding/Articles/CollectionOperators.html了解更多详情。

我不太了解您的模型,但我会假设我自己的模型可以为您提供解决方案,希望您觉得它很有趣。

假设我有一个名为Data的模型,如下所示;

@interface Data:NSObject
  @property(nonatomic, strong) NSString *name;
  @property(nonatomic) int day;
@end
@implementation Data
  @synthesize name, day;
@end

Now, in your some classes you create instances of data object and add it to an array.

NSMutableArray *myArray = [NSMutableArray array];
Data *data =[ [Data alloc] init];
data.name = @"First Name";
data.day = 10;
[myArray addObject:data];
data = [[Data alloc] init];
data.name = @"Second Name";
data.day = 20;
[myArray addObject:data];

Now, with this array you can play kvc game.

[myArray valueForKey:@"name"]

gives a new array as;

(First Name, Last Name)

[myArray valueForKey:@"day"] gives;

(10, 20 )

And for sum of all the days, you would just do,

[myArray valueForKeyPath:@"@sum.day"] and that would provide you with 30.

That's it. Hope I understood your question well. ;)

于 2012-11-27T19:05:47.443 回答