Sum of records in property list

五迷三道 提交于 2019-12-13 06:01:59

问题


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];
}


来源:https://stackoverflow.com/questions/17029616/sum-of-records-in-property-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!