开发者

What's wrong with my Objective-C?

Something's wrong with my code here and I can't quite figure it out.

Edit: Please correct this code. Thanks!

int stringLength = [theData length];
for (int i = 1; i <开发者_StackOverflow社区;= stringLength; i++) {
        unichar currentCharacter = [theData characterAtIndex:i];
        int currentCharacterCode = keyCodeForKeyString(currentCharacter);
        CGPostKeyboardEvent((CGCharCode)0, (CGKeyCode)currentCharacterCode, true);
        CGPostKeyboardEvent((CGCharCode)0, (CGKeyCode)currentCharacterCode, false);
}

- (int)keyCodeForKeyString:(unichar)keyString
{
    if (strcmp(keyString, "a") == 0) return 0;
    if (strcmp(keyString, "s") == 0) return 1;
    if (strcmp(keyString, "d") == 0) return 2;
    if (strcmp(keyString, "f") == 0) return 3;
    if (strcmp(keyString, "h") == 0) return 4;
}


For one thing, characterAtIndex is zero-indexed. So, you're starting at the second character of theData, and (assuming theData and theString have the same length) reading one past the end (which is undefined behavior). For another, characterAtIndex returns unichar, not a pointer-to-char. You're also calling keyCodeForKeyString on the pointer, when you should be passing it as a parameter. But you could change keyCodeForKeyString to take a unichar, rather than a one-character null-terminated string.


This line:

int currentCharacterCode = keyCodeForKeyString(currentCharacter);

is a problem. You don't seem to have a function called keyCodeForKeyString. You do have a method with that name, but the syntax for that would be

int currentCharacterCode = [self keyCodeForKeyString: currentCharacter];
//                          ^^^^ I assume you are sending the message from the same object.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜