开发者

Convert javascript function to Obj-C function

I want to use a bunch of functions that were written in Javascript in my Obj-C app. I made a header file and got the first one converted, but got stuck on the second. Here's what I started with and what I've done so far that doesn't work...

function calcDayOfWeek(juld)
    {
        var A = (juld + 1.5) % 7;
        var DOW =     (A==0)?"Sunday":(A==1)?"Monday":(A==2)?"Tuesday":(A==3)?"Wednesday":(A==4)?"Thursday":(A==5)?"Friday":"Saturday";
        return DOW;
    }

...and my attempt:

NSString calcDayOfWeek(float julianDay)
{
    float A = (julianDay + 1.5) % 7;
    NSString DOW = (A==0)?"Sunday":(A==1)?"Monday":(A==2)?"Tuesday":(A==3)?"Wednesday":(A==4)?"Thursday":(A==5)?"Friday":"Saturday";
    return DOW;
}

It should return a string with the day of the week based on the input of a Julian Day Number.

EDIT: Per Yuji's answer, this is what worked...

NSString* calculateDay开发者_Go百科OfWeek(float julianDay) {
    int a = fmod(julianDay + 1.5, 7);
    NSString* dayOfWeek = (a==0)?@"Sunday":(a==1)?@"Monday":(a==2)?@"Tuesday":(a==3)?@"Wednesday":(a==4)?@"Thursday":(a==5)?@"Friday":@"Saturday";
    return dayOfWeek;
}


You first need to learn the syntax and the grammar of Objective-C. The function would be

NSString* calcDayOfWeek(float julianDay)
{
     int A = ((int)(julianDay + 1.5)) % 7;
     NSString* DOW = (A==0)?@"Sunday":(A==1)?@"Monday":(A==2)?@"Tuesday":(A==3)?@"Wednesday":(A==4)?@"Thursday":(A==5)?@"Friday":@"Saturday";
     return DOW;
}
  • In Objective-C, variables for objects are pointers, not the object itself. You need NSString* instead of NSString.
  • @"..." is the Objective-C string which is an object. "..." is a C-string, which is just char*.
  • I recommend against using == for a float. What happens if two floats differ by .00000001? Well, % operator automatically gives you integer, but I still don't like it.

However, you shouldn't re-invent the wheel. Cocoa has an API that does the calendar conversion for you. See Date and Time Programming Topics.


You'll need to change the way you declare the function. Try this:

-(NSString *) dayOfWeek:(float)julianDay {

    float A = (julianDay + 1.5) % 7;
    NSString *DOW = (A==0)?@"Sunday":(A==1)?@"Monday":(A==2)?@"Tuesday":(A==3)?@"Wednesday":(A==4)?@"Thursday":(A==5)?@"Friday":@"Saturday";
    return DOW;
}


You'll want to build your strings as NSStrings by prefixing them with @s and take a reference to them:

NSString *calcDayOfWeek(float julianDay)
{
    float A = (julianDay + 1.5) % 7;
    NSString *DOW = (A==0)?@"Sunday":(A==1)?@"Monday":(A==2)?@"Tuesday":(A==3)?@"Wednesday":(A==4)?@"Thursday":(A==5)?@"Friday":@"Saturday";
    return DOW;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜