一千萬個為什麽

搜索

獲得最小值和最大值

所以我有一系列自定義對象。我想通過它們找到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

我無法弄清楚為什麽這段代碼不起作用。

最佳答案

這條線......

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

...暗示 -minx-miny-maxx-maxy 的返回值都是對象,很可能是 NSNumber 對象。

If that's the case, then you can't use < and > to compare two NSNumbers. You'd be doing pointer comparison, which is most definitely not what you want.

所以你可以做的是:

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次而不是一次,但如果您的列表是合理的大小,則差異可能可以忽略不計。

轉載註明原文: 獲得最小值和最大值