开发者

NSArray - getting the closest object to origin

using Objective-C for iPhone, I'm attempting to gather the closest object to my origin.

All my objects are in an NSMutableArray and have CGPoint property of their current location.

Using simple trig I can find the magnitudes of all my o开发者_StackOverflow社区bjects with ease, but Im trying to find the 'closest' object to my origin. Does anyone have any idea how to do this?


loop through all the objects, calculate the distance to your origin while keeping the minimum value?

distanceAO = sqrt(sqr(Ax-Ox)+sqr(Ay-Oy))


Do you mean something like:

CGFloat minDistance = FLT_MAX;
MyClass *minObject = nil;
for (MyClass *obj in objects)
{
    if ([obj distanceFromOrigin] < minDistance)
    {
        minObject = obj;
        minDistance = [obj distanceFromOrigin];
    }
}


there are sorting methods for NSArray which easies your work. have a look at this link

i am not sure exactly which method solves your case but have a look into those methods you can definitely achieve it

TNQ

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜