Sum of records in property list

2019-08-19 04:21发布

问题:

How can I calculate the sum of all numbers in all dictionaries for the key for example "Hours"?

Couldn't find any informations about that.

Here is piece of my property list I'm talking about:

<plist version="1.0">
<array>
    <dict>
        <key>Address1</key>
        <string>17 Stanley Road</string>
        <key>Address2</key>
        <string>Essex</string>
        <key>City</key>
        <string>Southend On Sea</string>
        <key>Email</key>
        <string>lmozdzen@gmail.com</string>
        <key>Lessons</key>
        <array>
            <dict>
                <key>LessonComment</key>
                <string></string>
                <key>LessonDate</key>
                <string>05/06/2013</string>
                <key>LessonHomework</key>
                <string></string>
                <key>LessonHours</key>
                <integer>1</integer>
                <key>LessonNext</key>
                <string></string>
                <key>LessonNumber</key>
                <string>1</string>
                <key>LessonTime</key>
                <string></string>
            </dict>
            <dict>
                <key>LessonComment</key>
                <string>Ryun</string>
                <key>LessonDate</key>
                <string></string>
                <key>LessonHomework</key>
                <string>T</string>
                <key>LessonHours</key>
                <integer>2</integer>
                <key>LessonNext</key>
                <string>Ty</string>
                <key>LessonNumber</key>
                <string>4</string>
                <key>LessonTime</key>
                <string></string>
            </dict>
        </array>

I want the sum of all numbers for key "LessonHours"

回答1:

Using Key Value Coding:

NSNumber *sum = [[yourDict allKeys] valueForKeyPath:@"@sum.theIntegerPropertyToSum"];

Or you can use plane old style addition using loop.

NSInteger sum=0;
for(NSString *string in yourDict){
    sum+=[string integerValue];
}