简体   繁体   中英

Exposing a property as readonly

I'm writing framework and want to expose certain internal property as readonly. So I added a readonly property in the header and synthesize it manually like this.

-(NSMutableURLRequest*) readonlyRequest {

    return [self.request copy];
}

The caller gets a copy which can still be mutated, but doesn't affect the internal property. Is this the right way to do? Or are there some other better alternatives?

The code is compiled for ARC, so no autorelease

That's actually incorrect. The caller will get an NSURLRequest* . You need to use -mutableCopy instead.

- (NSMutableURLRequest *)readonlyRequest {
    return [self.request mutableCopy];
}

Alternatively, you should declare this as just NSURLRequest * (which is probably better, unless you have some reason to think the caller needs a mutable request).

Edit: Removed the bit about autorelease because the question was updated to indicate this is ARC.

Usually if it's read only you would return a non mutable copy.
But yes that is the way.
And if you store a readonly property as an immutable object, since it's immutable you can just sent the object, the caller won't be able to modify your object.

I'm not sure if conceptually it makes sense to have a mutableCopy in a readonly property. Maybe someone could give some examples of when it does to fill in some gaps in my thinking?

  • I can't do a comparison without wondering if the object I have has been mutated since I received it
  • If I receive an object from a class that I can mutate I generally assume I am mutating the instance in the class not a copy. This will likely lead to me doing some head scratching until I look closer at the header file to see what's going on - this of course is not as relevant in this case as you include readonly in the @property name, which is often not the case.

I think semantically it is weird to get back a mutable result from a read-only property. The implication of read-only is the class not wanting the object changed, yet you are given an object where seemingly you can do so - even if behind the scenes it's really a copy it's not something expected.

Instead of a property I would make that just an accessor method like mutableCopyOfMyData , something that is clearer as to intent for the user to modify the result as they will.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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