且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将一个字符串与objective-C中的数组进行比较

更新时间:2022-12-27 14:09:39

您的代码似乎工作正常。它的可怕的代码,但它工作正常,//不做任何部分被调用任何匹配和//做某事部分被称为数组中的每个不匹配。我怀疑的问题是,你期望//无用的部分执行一次,如果没有匹配,和//做某一部分执行一次,如果有任何匹配,这不是这种情况。您可能想要:

Your code appears to work fine. Its terrible code, but it works fine, the // do nothing section is called for any match and the // do something section is called for each mismatch in the array. I suspect the problem is that you are expecting the // do nothing section to be executed once if there is no match, and // do something section to be executed once if there is any match, which is not the case. You probably want:

-(void) findRedundant: (NSString *) aString {
#define ALPHA_ARRAY [NSArray arrayWithObjects: @"A", @"B", @"C", nil]
    BOOL found = NO;
    NSUInteger f;
    for (f = 0; f < [ALPHA_ARRAY count]; f++) {
        NSString * stringFromArray = [ALPHA_ARRAY objectAtIndex:f];
        if ([aString isEqualToString:stringFromArray]) {
            found = YES;
            break;
        }
    }
    if ( found ) {
        // do found
    } else {
        // do not found
    }
}

此外,你显然不明白宏,何时应该和不应该使用它们一般来说,你应该永远不要使用它们,只有很少的例外)。宏是文本替换到您的代码。这意味着阵列创建和初始化每次都会使用ALPHA_ARRAY。这是可怕的。

Also, you clearly do not understand macros and when you should and should not use them (generally, you should never use them, with very few exceptions). The macro is textually substitued in to your code. That means the array creation and initialization is happening every time you use ALPHA_ARRAY. This is terrible.

基本上,不要再使用#define(除了常量),直到你对你的工作有了更深的把握。在这种情况下,你将创建数组为taebot描述:

Basically, never use #define again (except for constants) until you have a much deeper grasp of what you're doing. In this case, you would create the array as taebot described:

NSArray* alphaArray = [NSArray arrayWithObjects: @"A", @"B", @"C", nil];

接下来,如果您正在开发一个现代平台(10.5或iPhone),可以使用快速枚举这更容易和更清楚地阅读:

Next, if you are developing for a modern platform (10.5 or iPhone), you can use Fast Enumeration which is much easier and clearer to read:

-(void) findRedundant: (NSString *) aString {
    NSArray* alphaArray = [NSArray arrayWithObjects: @"A", @"B", @"C", nil];
    BOOL found = NO;
    for ( NSString* stringFromArray in alphaArray ) {
        if ([aString isEqualToString:stringFromArray]) {
            found = YES;
            break;
        }
    }
    if ( found ) {
        // do found
    } else {
        // do not found
    }
}

最后,你应该阅读关于NSArray和NSString的文档,可以免费使用,然后你会发现像KiwiBastard指出的方法,你可以重写你的例程:

And finally, you should go read through the documentation on NSArray and NSString to see what you can do for free, and then you'll find methods like containsObject that KiwiBastard pointed out, and you can rewrite your routine as:

-(void) findRedundant: (NSString *) aString {
    NSArray* alphaArray = [NSArray arrayWithObjects: @"A", @"B", @"C", nil];
    if ( [alphaArray containsObject: aString] ) {
        // do found
    } else {
        // do not found
    }
}