Search code examples
objective-cheaderstatic-librariesreadonly-attribute

property is readonly on static library


I have a class with some properties, some of them have to be read-only or they could cause system problems.

An example would be the following:

Button.h

@property (nonatomic, strong, readonly) NSString *button_id;

The problem I have with this is that I am going to deliver the code as a static library, but I don't want someone to be able to change the header code and allow the variable to be writable.

As you can see, I don't have much idea of ​​Objective C, what would be the best strategy to avoid something like this?


Solution

  • In Objective-C, you can easily circumvent the readonly annotation and the general agreement is sort of that somebody else won't mess with the code in that way, unless he wants to ...

    What I am saying is that you should just mark it as readonly as you do now and not worry too much. If you are dealing with some sensitive stuff that really should not be changed you need to do it differently using e.g. encryption but below at least is a way to make it a bit stronger than just readonly.

    The code below does not rely on a property, but rather on a class method. You could also use an instance method but here class makes more sense. This immediately causes it to be not settable, so you dodge a lot of cases where somebody may intentionally or accidentally set it. You also take it out of the header file and firmly into the (compiled) class file.

    The direct attribute further means that it can not be overridden in a subclass. This is about as good as it gets. It is complete overkill for button IDs in a UI and not enough for e.g. a bank account, but is about as strong as you can make it.

    Header file / interface

    + ( NSString * ) password __attribute__ ( ( objc_direct ) );
    

    Implementation

    + ( NSString * ) password __attribute__ ( ( objc_direct ) )
    {
        return @"abc";
    }
    

    Use

    NSLog ( @"The password is %@", MyClass.password );
    

    EDIT

    FWIW if you just want to have a bunch of read-only IDs, simply go with something like below in the header

    + ( NSString * ) id1;
    + ( NSString * ) id2;
    

    and implement it something like this

    + ( NSString * ) id1 { return @"1"; }
    + ( NSString * ) id2 { return @"2"; }