【问题标题】:ios 6 and 7 doesnt return same resultsios 6 和 7 不返回相同的结果
【发布时间】:2013-09-19 17:57:10
【问题描述】:

似乎我们使用getPropertyType(..) 的应用程序在 ios7 下失败了。无论出于何种原因,getPropertyType(..) on 例如一个 NSString 属性返回 NSString$'\x19\x03\x86\x13 作为类型,而不仅仅是 NSString,也不是 NSNumber,它返回 NSNumber\xf0\x90\xae\x04\xff\xff\xff\xff。当我稍后检查特定类型时,所有这些都导致了一些棘手的问题。我已将此(旧版?)代码更改为使用 isKindOfClass,但令我困扰的是我不明白这里发生了什么。

有问题的代码:

#import <objc/runtime.h>

static const char *getPropertyType(objc_property_t property) {
    const char *attributes = property_getAttributes(property);
    char buffer[1 + strlen(attributes)];
    strcpy(buffer, attributes);
    char *state = buffer, *attribute;
    while ((attribute = strsep(&state, ",")) != NULL) {
        if (attribute[0] == 'T') {
            return (const char *)[[NSData dataWithBytes:(attribute + 3) length:strlen(attribute) - 4] bytes];
        }
    }
    return "@";
}

到底是怎么回事,为什么结果不一样??

【问题讨论】:

    标签: ios objective-c objective-c-runtime


    【解决方案1】:

    getPropertyType 返回的缓冲区不是 NULL 终止的。我认为它曾经奏效只是愚蠢的运气。此外,返回新创建的 NSData 所指向的数据并不能保证在该函数返回后正常工作。

    我会让它返回一个 NSString。

    NSString* getPropertyType(objc_property_t property) {
        const char *attributes = property_getAttributes(property);
        char buffer[1 + strlen(attributes)];
        strcpy(buffer, attributes);
        char *state = buffer, *attribute;
        while ((attribute = strsep(&state, ",")) != NULL) {
            if (attribute[0] == 'T') {
                return [[NSString alloc] initWithBytes:attribute + 3 length:strlen(attribute) - 4 encoding:NSASCIIStringEncoding];
            }
        }
        return @"@";
    }
    

    这假定为 ARC。

    【讨论】:

      【解决方案2】:

      方法的返回值不需要以 NULL 结尾,因为它 指向NSData 对象的内部存储器。 这将解释您预期输出后的随机字节。

      还要注意,如果 NSData 对象,返回值可能根本不指向有效内存 被销毁(可能在您的函数返回后的任何时间)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-02
        • 1970-01-01
        • 2019-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多