有什么更好的方法来检查string是否是const结构的成员?

时间:2013-09-26 10:43:15

标签: ios objective-c string struct

我想检查字符串是否在const结构中。我这样做是这样的:

在我的MyClass.h中:

extern const struct MyAttributes {
    __unsafe_unretained NSString *attribute1;
    __unsafe_unretained NSString *attribute2;
    __unsafe_unretained NSString *attribute3;
    __unsafe_unretained NSString *attribute4;
    __unsafe_unretained NSString *attribute5;
} MyAttributes;

然后在我的MyClass.m中我有:

const struct MyAttributes MyAttributes = {
    .attribute1 = @"attribute1",
    .attribute2 = @"attribute2",
    .attribute3 = @"attribute3",
    .attribute4 = @"attribute4",
    .attribute5 = @"attribute5"
};

...

- (void)someMethod
{
    BOOL test1 = [self check:@"test"];
    BOOL test2 = [self check:@"attribute1"];
}

- (BOOL)check:(NSString *)string
{
    return [string isEqualToString:MyAttributes.attribute1] ||
        [string isEqualToString:MyAttributes.attribute2] ||
        [string isEqualToString:MyAttributes.attribute3] ||
        [string isEqualToString:MyAttributes.attribute4] ||
        [string isEqualToString:MyAttributes.attribute5];
}

嗯,这很有效。但是,是否有更好的方法来实施- (void)check,以便在我更新MyAttributes时,我不必更新- (void)check

2 个答案:

答案 0 :(得分:1)

您可以将其转换为Objective-C数组,然后查看它是否包含您要查找的字符串:

- (BOOL) check: (NSString*) string {
    // I renamed the variable MyAttributes to myAttributes, following naming conventions
    __unsafe_unretained id* ptr;
    struct MyAttributes* attrPtr= &myAttributes;
    memcpy(&ptr, &attrPtr, sizeof(id*));
    NSArray* array= [NSArray arrayWithObjects: ptr count: sizeof(MyAttributes)/sizeof(NSString*)];
    return [array containsObject: string];
}

C风格的方法是将结构视为C数组:

- (BOOL)check:(NSString *)string {
    BOOL result= NO;
    // I renamed the variable MyAttributes to myAttributes, following naming conventions
    NSString* __unsafe_unretained * strPtr;
    struct MyAttributes* ptr= &myAttributes;
    memcpy(&strPtr, &ptr, sizeof(NSString**));
    for(size_t i=0; i<sizeof(MyAttributes)/sizeof(NSString*) && !result;i++) {
        result= [string isEqualToString: strPtr[i] ];
    }
    return result;
}

PS:我使用memcpy来避免桥接,因为字符串已经保留在myAttributes中。

答案 1 :(得分:0)

你可以在NSArray中保留结构项的方向

可能的答案:

Cocoa structs and NSMutableArray

然后在- check方法中使用containsObject:或数组迭代来检查字符串是否存在。