开发者

NSArray - getting the closest object to origin

开发者 https://www.devze.com 2023-03-16 08:52 出处:网络
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 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

精彩评论

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

关注公众号