获得最小值和最大值

时间:2011-09-28 21:05:58

标签: objective-c

所以我有一系列自定义对象。我想通过它们找到maxx,maxy,minx和miny值。我需要最大的最大和最小的分钟。下面的代码对我来说很有意义,但我倾向于从列表中得到一个随机值,我的最大值不会达到最大值或最小值,并且分钟不会得到最小值或最大值。

所以,我从数组中的第一个对象获取第一个值,然后将每个对象值与我当前的maxx,maxy,minx,miny进行比较,以查看对象的值是大于还是小于,如果是,分配它:

        claimCenterBoundary = [dataCenter.claimCenterBoundaryList objectAtIndex:0];
        maxx = claimCenterBoundary.maxx;
        maxy = claimCenterBoundary.maxy;
        minx = claimCenterBoundary.minx;
        miny = claimCenterBoundary.miny;

        for (int i = 0; i < count; i++) 
        {
            claimCenterBoundary = [dataCenter.claimCenterBoundaryList objectAtIndex:i];
            NSLog(@"minx: %@ miny: %@ maxx: %@ maxy: %@", claimCenterBoundary.minx, claimCenterBoundary.miny, claimCenterBoundary.maxx, claimCenterBoundary.maxy);

            if (maxx < claimCenterBoundary.maxx)
                maxx = claimCenterBoundary.maxx;

            if (maxy < claimCenterBoundary.maxy)
                maxy = claimCenterBoundary.maxy;

            if (minx > claimCenterBoundary.minx)
                minx = claimCenterBoundary.minx;

            if (miny > claimCenterBoundary.miny)
                miny = claimCenterBoundary.miny;
        }

这是我的输出:

count: 8
minx: -98.9139404296875 miny: 48.51737594604492 maxx: -98.90547943115234 maxy: 48.52248382568359
minx: -98.9139404296875 miny: 48.51737594604492 maxx: -98.90547943115234 maxy: 48.52248382568359
minx: -98.92726898193359 miny: 48.51534652709961 maxx: -98.91975402832031 maxy: 48.52249908447266
minx: -98.92726898193359 miny: 48.51534652709961 maxx: -98.91975402832031 maxy: 48.52249908447266
minx: -98.92340850830078 miny: 48.51531219482422 maxx: -98.91383361816406 maxy: 48.52248382568359
minx: -98.92340850830078 miny: 48.51531219482422 maxx: -98.91383361816406 maxy: 48.52248382568359
minx: -98.909423828125 miny: 48.51529693603516 maxx: -98.90548706054688 maxy: 48.51742553710938
minx: -98.96006774902344 miny: 48.51530075073242 maxx: -98.94926452636719 maxy: 48.52977752685547
final minx :-98.92726898193359 miny: 48.51531219482422 maxx: -98.94926452636719 maxy: 48.52977752685547

我无法弄清楚为什么这段代码不起作用。

1 个答案:

答案 0 :(得分:7)

这一行...

NSLog(@"minx: %@ miny: %@ maxx: %@ maxy: %@", claimCenterBoundary.minx, claimCenterBoundary.miny, claimCenterBoundary.maxx, claimCenterBoundary.maxy);

...意味着-minx-miny-maxx-maxy的返回值都是对象,很可能是NSNumber个对象。< / p>

如果是这种情况,则您无法使用<>来比较两个NSNumbers。您将进行指针比较,这绝对是您想要的。

所以你能做的就是:

NSArray *objects = dataCenter.claimCenterBoundaryList;
NSNumber *minx = [objects valueForKeyPath:@"@min.minx"];
NSNumber *miny = [objects valueForKeyPath:@"@min.miny"];
NSNumber *maxx = [objects valueForKeyPath:@"@min.maxx"];
NSNumber *maxy = [objects valueForKeyPath:@"@min.maxy"];

技术上,这比原始提案的效率低4倍,因为您要将整个列表迭代4次而不是一次,但如果您的列表是合理的大小,那么差异可能可以忽略不计。