Search code examples
macosnsviewreadonly-attribute

Setting NSView readonly-property tag on subclass


I have a class derived from NSView. NSView has a declaration

@property (readonly) NSInteger tag;

How can I set tag property to some value in my subclass? I tried following in my header file

@property(readwrite, assign) NSInteger tag;

Then in implementation I have

@dynamic tag
...
- (void)setTag:(NSInteger)newTag
{
    _tag = newTag;
}

This does not compile, I get 'Use of undeclared identifier: '_tag'. How can I set tag to a value?


Solution

  • I think the issue you're hitting is that _tag doesn't exist in the context where you're trying to set it, but if you use @synthesize like this:

    #import <Cocoa/Cocoa.h>
    
    @interface SOView : NSView
    
    @property (readwrite) NSInteger tag;
    
    @end
    
    
    @implementation SOView
    
    @synthesize tag = _tag;
    
    - (void)awakeFromNib
    {
        self.tag = 25;
    }
    
    @end
    

    I tried this out in my own tiny test project and it worked perfectly fine.