简体   繁体   English

如何比较声明为ID的实例 <protocol> 在Objective-C中

[英]How to compare instances declared as id<protocol> in Objective-C

I have a class that has a property declared as type id that adheres to a protocol and I'd like to ensure equality for it. 我有一个类,该类具有声明为类型ID的属性,该属性遵守协议,因此我想确保其相等性。

How do check for value equality on an property declared as type id ? 如何检查声明为id类型的属性的值相等性?

@interface MyClass : NSObject
    @property (nonatomic, copy) NSString *name;
    @property (nonatomic, strong) id<SomeProtocol> attribute;
@end

@implementation MyClass 

- (BOOL)isEqual:(id)object {
    if (self == object) {
        return YES;
    }

    if (![object isKindOfClass:[MyClass class]]) {
        return NO;
    }

    return [self isEqualToMyClass:(MyClass *) object];
}

- (BOOL)isEqualToMyClass:(MyClass *)rhsValue {
    if (rhsValue == nil) {
        return NO;
    }

    return 
        ([self.name isEqualToString:rhsValue.name] && 
        // Compiler produces error: Error:(90, 36) no known instance method for selector 'isEqual:'
        [self.attribute isEqual:rhs.attribute]); 
}

@end

SomeProtocol is defined as: SomeProtocol定义为:

@protocol SomeProtocol <NSObject>

@end

Class that extends SomeProtocol : 扩展SomeProtocol类:

@interface MyAttributeClass : NSObject <SomeProtocol>

@end

MyAttributeClass implements the protocol SomeProtocol and it has its own isEqual and when an instance of it is stored by MyClass in attribute, I'd like to be able to check that the values are equivalent. MyAttributeClass实现协议SomeProtocol ,它具有自己的isEqual,当MyClass将其实例存储在attribute中时,我希望能够检查这些值是否相等。

It is MyAttributeClass that gets assigned into MyClass: 分配给MyClass的是MyAttributeClass:

MyClass *myClass = [[MyClass alloc] init];
myClass.name = "HAL";
myClass.attribute = [[MyAttributeClass alloc] init];

Probably you forgot to import the header containing the protocol definition. 您可能忘记了导入包含协议定义的标头。 (Instead of only having a forward declaration.) Add that in front of the implementation. (而不是仅具有前向声明。)在实现之前添加该声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM