简体   繁体   中英

Objective-C: Getters should not be used for side effects compiler warning

Can someone clarify what is happening here. I got an class called: brainModel and it again has an NSArray called: operandStack. I am simply accessing the array sending it the message "removeAllObjects"

self.brainModel.operandStack.removeAllObjects;

but using dot notation it gives me an warning "Property access result unused - getters should not be used for side effects" What exactly does this mean?

using nested bracket syntax like this gives no warning:

 [[[self brainModel]operandStack]removeAllObjects];

both works btw... does it have anythig to do with wrong use of dot notation? or is it considered good practice to use dot notation when messaging objects like this - sending it arguments like "removeAllObjects".

removeAllObjects is not a property; it's a method.

Using property-access notation works because properties are usually accessed using a method of the same name. However, it is expected that getting a property's value will not change the object which contains the object (or make any other changes), which is not the case with removeAllObjects . These are the "side effects" that the compiler is referring to.

Probably, you would want to perform this call instead:

[self.brainModel.operandStack removeAllObjects];

This gets the brainModel property of self , then the operandStack property of self.brainModel , then calls removeAllObjects on it.

removeAllObjects is a method. You cannot access methods through dot notation; only properties.

You don't need to declare each and every method as a property - especially not if they are modifying the object. Getters should be viewed as accessors to a property (without exposing the backing ivar directly). Methods that are 'actions', to say, are to be declared as such (ie declared without the @property keyword and called using brackets instead of the dot notation).

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