0

I'm having some issues trying to override a property in a protocol to make it mutable.

I have this protocol:

@protocol TheProtocol
     @property (nonatomic, readonly) NSString *someString;
@end

And this class:

@interface SuperObject : NSObject <TheProtocol>
@end

Which synthesizes the variable like so:

@implementation SuperObject
@synthesize someString;

-(id)init {
 if(self=[super init]) {
    someString = [aString copy];
 }
 return self;
 }

@end

and can thus write to it internally

I then have a subclass:

@interface SubObject : SuperObject 
@end

@implementation SubObject
@synthesize someString;

- (id)init {
  if(self=[super init]) {
    NSLog(@"Some string is %@",someString");
    someString = [bString copy];
  }
  return self;
}

In my subclass, trying to assign to someString doesn't work. I tried also synthesizing someString in my subclass but before I try and modify it, when I print out "someString", it prints nil instead of "something"

Answered

I figured out the answer. Ultimately what worked is this:

@interface SuperObject : NSObject <TheProtocol> {
     @protected
     NSString *someString;
}
@end
4

1 回答 1

1

发生的情况是,当您在子类中进行综合时,分配的 ivar 与超类中的 ivar 不同。因此打印时的值为nil。您可以通过执行参考原始 ivarself.someString.

希望有帮助。

于 2013-09-30T19:30:00.570 回答