0

我想检查字符串是否在 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

4

2 回答 2

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.

于 2013-09-26T11:58:51.037 回答
0

您可以在 NSArray 中保留结构项目的方向进行挖掘

可能的答案:

Cocoa 结构和 NSMutableArray

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

于 2013-09-26T10:52:52.207 回答