For a D range, should front() be a #property? - properties

When I define my D range, should front() be a #property? (or just a
"regular" member function?)

Yes, it is supposed to be (the formal definition is under the isInputRange template in the docs, see: http://dpldocs.info/experimental-docs/std.range.primitives.isInputRange.html ).
In practice, it may work anyway, but since the docs say it and typeof(range.front) is a common check in range constraints and that is the one thing #property will actually change in the dmd implementation right now, it is best to use it to be compliant.
Now, #property currently does not prohibit calling it like range.front(), with parenthesis, you should NOT do that, since at some point in the future, #property might change to block that behavior.
So yeah, use #property on range.front and always use it as a property for maximum forward compatibility.

Related

Is it OK to have a method's variable with the same name as a declared property?

I understand this is probably bad practice, but I was just curious as to whether or not this has any negative side-effects, in Objective-C (trying to learn as much as I can):
#interface MyClass ()
// Declare a string called 'foo'
#property (nonatomic, strong) NSString *foo
#end
#implementation MyClass
...
- (void)modifyFoo {
// Create a local variable with the same name as a property
NSString *foo = #"Hello!" // No compiler warnings?
self.foo = foo; // <---- Is this OK?
}
This will not throw up a warning in the compiler, and sure enough, my code works as normal. If there are zero negative side-effects, does the type of property, e.g. weak/strong/assign, etc, have an influence on whether or not this is OK?
Note: I am aware that this will not work when the property is synthesised.
This is fine and is my personally preferred approach. The reason no compiler warning is generated is that the instance variable is actually named _foo. This is done by the auto-synthesise added by the compiler (it generates #synthesize foo = _foo for you). Maintaining naming consistency aids clarity.
The main potential side effect is that you inadvertently add / fail to add self. and end up trying to message nil.
Firstly:
this will not work when the property is synthesised.
Huh? Why not?
Actually, it's "OK" in the sense that it works. Actually, there's no ambiguity when you use the self keyword and the dot notation to access your property. If, however, you had an instance variable with the same name as your local variable, then the object with a narrower scope (the local variable in this case) hides the one with a wider scope (the ivar). And that may be undesirable. As far as I know, it even results in a compiler warning. Furthermore, it's hard to get it wrong and decreases overall code readability, so don't do this if you have that identically named instance variable.
If I recall correctly, recent versions of the clang/LLVM toolchain automatically synthesize properties for you, and the name of the backing ivar for a property is preceded by a leading underscore, so this should not be a problem.

Objective-c properties for primitive types

In Objective-C Does it ever make sense to specify a property for a primitive type as nonatomic?
I'm wondering about the difference between these two properties:
#property (nonatomic) BOOL myBool;
#property BOOL myBool;
The answer is technically YES they're different, but practically NO they're not, unless you code your own accessors.
Let me explain. For an object pointer property, say #property NSObject *foo there is a clear and important difference in the code that gets generated if you use synthesize the accessors. This is described in the Apple documentation where it points out that the synthesized accessors will lock the object if the property is atomic (if you don't specify nonatomic, it becomes atomic by default)
So for object properties In a very crude nutshell: nonatomic is faster but not threadsafe, atomic (you can't specify it, but its the default) is threadsafe but potentially slower.
(Note: if you're accustomed to Java, you can think of using nonatomic as like not specifying synchronized, and not specifying nonatomic as like specifying synchronized. In other words atomic = synchronized)
But a BOOL is a primitive - in fact a C signed char, so access should be atomic without locking the object as mentioned in Jano's answer. So when you're synthesizing the accessor, there are two possibilities:
1: the compiler is smart and sees that the property is primitive and avoids locking it, and
2: the compiler always locks the object for atomic properties
As far as I can see this is not documented anywhere, so I tried it by using the Generate->Assembly option in XCode and comparing it. The answer was not completely conclusive, but close enough to say that I'm almost certain the answer is #1, the compiler is smart. I say this, because the assembly code generated for an atomic object property is considerably different (more of it) than for a non-atomic object property: this is all the code for locking the object. For a BOOL property on the other hand, there was only one line different - a single "mov" which doesn't look like it could possibly make a difference. Still I wonder. Interestingly, another difference is that the atomic version of BOOL has some extra commented-outlines for debugging - so the compiler is clearly treating it differently.
Nonetheless the similarity is such that I would say they're the same for practical purposes.
But they're still technically different and may be substantively different in some other library you're reading (that you didn't code yourself) if you can't see the implementation, and here's why: atomic properties have a contract. The contract says: "If you access my value on multiple threads, I promise that each setting or getting operation will complete before any other begins".
But, you say, BOOL is still naturally atomic, so isn't this contract implicit?
No. A BOOL variable is naturally atomic, but we're talking about a property. A property might not be synthesized and might not even have a single variable to back it up. This is actually pretty common. Consider:
#property (getter=isEmptyThingo) BOOL emptyThingo;
...
- (BOOL)isEmptyThingo
{
Thingo *thingo = [self deriveTheThingo];
if ([thingo length] == 0) {
return YES;
}
return NO;
}
who knows what's going on in deriveTheThingo!?
Okay, this is a bit contrived, but the point is that isEmptyThingo - our getter doesn't look very atomic, does it? What happens if one thread is deriving the thingo and another thread comes calling to find if its empty.
Long story short: the property is not atomic. So we should declare it so.
Hence m original answer qualified: if you're writing this property yourself and using #synthesize, then they're probably the same, but you should generally not treat them the same.
As a rule of thumb, if you don't need multithreaded support - which you generally don't if you're working in UI code like UIViewControllers, then just declare it all nonatomic.
In a x-bit architecture (eg: 32bit, 64bit, etc.) any value which is x or less bits will always be read or written atomically. This is a property of any sane hardware implementation.
The default atomic property means that a property value is always set or get in whole, disregarding what other threads are doing. This is only a concern for properties that exceed the number of bits of the architecture. Nonatomic is completely ignored by the compiler on any other type.
Example:
#property struct { int d; } flag;
#property (atomic) struct { float x; float y; } point;
#property (atomic,copy) NSString *s;
struct { int d; } is already atomic so the accesors don't need mutual exclusion.
struct { float x, float y} could be in an inconsistent state if it wasn't atomic. Example: two threads setting {1,2} and {3,4} could overlap the writing, and the struct could end up with a value from each set: {1,4}.
Pointers are stored in a single memory position but they require several statements for memory management.
Atomic properties contribute to thread safety avoiding race conditions that lead to inconsistent values or memory management mishaps. This alone doesn't guarantee thread safety because it doesn't deal with other problems like deadlock, starvation, visibility, etc.
Yes. nonatomic is not a memory-management keyword, it has to do with thread safety. Also, properties are atomic by default (without explicitly declaring them as nonatomic), so there is a difference between the two declarations you listed.

Why do properties require explicit typing during compilation?

Compilation using property syntax requires the type of the receiver to be known at compile time. I may not understand something, but this seems like a broken or incomplete compiler implementation considering that Objective-C is a dynamic language.
The property "comment" is defined with:
#property (nonatomic, retain) NSString *comment;
and synthesized with:
#synthesize comment;
"document" is an instance of one of several classes which conform to:
#protocol DocumentComment <NSObject>
#property (nonatomic, retain) NSString *comment;
#end
and is simply declared as:
id document;
When using the following property syntax:
stringObject = document.comment;
the following error is generated by gcc:
error: request for member 'comment' in something not a structure or union
However, the following equivalent receiver-method syntax, compiles without warning or error and works fine, as expected, at run-time:
stringObject = [document comment];
I don't understand why properties require the type of the receiver to be known at compile time. Is there something I am missing? I simply use the latter syntax to avoid the error in situations where the receiving object has a dynamic type. Properties seem half-baked.
Compiling property access requires knowing how to translate the property name into the correct getter/setter name. Without knowing the type of the receiver, the compiler cannot possibly know what the getter/setter is called, as the property may have overridden the name as part of its declaration, like so:
#property (nonatomic, retain, getter=myComment) NSString *comment;
If the compiler were to go ahead and generate code for your untyped example, it would generate [document comment], which will fail at runtime as the correct generated code is actually [document myComment].
Kevin nailed one of the symptoms.
When designing properties, the very specific decision was made not to support id as the target of dot syntax. Beyond the ambiguities that Kevin points out, the desire to avoid all ambiguities related to (id) receivers was considered desirable.
In general, the use of fully unqualified id is both undesirable and actively discouraged. In creating new features in the language, not supporting id discourages the proliferation fragile coding patterns across the new feature(s).

Objective-C synthesize property name overriding

I am trying to understand the purpose of the synthesize directive with property name overriding. Say that I have an interface defined as follow:
#interface Dummy ... {
UILabel *_dummyLabel;
}
#property (retain, nonatomic) UILabel *dummyLabel;
And in the implementation file, I have:
#synthesize dummyLabel = _dummyLabel;
From what i understand, "dummyLabel" is just an alias of the instance variable "_dummyLabel". Is there any difference between self._dummyLabel and self.dummyLabel?
Yes. self._dummyLabel is undefined, however _dummyLabel is not.
Dot syntax expands out to simple method invocations, so it's not specific to properties. If you have a method called -(id)someObject, for example in the case of object.someObject, it will be as if you wrote [object someObject];.
self.dummyLabel //works
self._dummyLabel //does not work
dummyLabel //does not work
_dummyLabel //works
[self dummyLabel]; //works
[self _dummyLabel]; //does not work
Your understanding is incorrect. dummyLabel is the name of the property, and is not an alias for the instance variable - the instance variable is only called _dummyLabel. So the following holds for an instance of Dummy called myObject:
[myObject dummyLabel] works
myObject.dummyLabel works
[myObject _dummyLabel] fails
myObject._dummyLabel fails
myObject->dummyLabel fails
myObject->_dummyLabel depends on the visibility of the ivar (#public, #private, #protected)
[myObject valueForKey: #"dummyLabel"] works
[myObject valueForKey: #"_dummyLabel"] depends on the implementation of +accessInstanceVariablesDirectly (i.e. it will work in the default case where +accessInstanceVariablesDirectly returns YES).
The advantage of having another name
for the ivar than for the property is
that you can easily see in the code
when you are accessing one or the
other - Andre K
I'm not able to find a 'comment' button so I'm having to post as an 'answer'.
Just wanted to expand on Andre's comment - by knowing when you are using the synthesized properties vs the vanilla variable, you know (especially in case of setters) when a variable is being retained/copied/released automatically thanks to your nice setter, vs being manipulated by hand.
Of course if you are doing things right, you probably don't need the help of a setter to retain/release objects properly! But there can be other scenarios too where referring to your ivars as self.ivar instead of _ivar can be helpful, such as when you are using custom setters/getters instead of the default synthesized ones. Perhaps every time you modify a property, you also want to store it to NSUserDefaults. So you might have some code like this:
#interface SOUserSettings : NSObject {
BOOL _autoLoginOn;
}
#property (nonatomic, assign) BOOL autoLoginOn;
#end
#implementation SOUserSettings
#synthesize autoLoginOn = _autoLoginOn;
- (void)setAutoLoginOn:(BOOL)newAutoLoginOnValue {
_autoLoginOn = newAutoLoginOnValue;
[[NSUserDefaults standardUserDefaults] setBool:_autoLoginOn forKey:#"UserPrefAutoLoginOn"];
}
#end
Note: This is just illustrative code, there could be a thousand things wrong with it!
So now, in your code, if you have a line that says _autoLoginOn = YES - you know it's not going to be saved to NSUserDefaults, whereas if you use self.autoLoginOn = YES you know exactly what's going to happen.
The difference between _autoLoginOn and self.autoLoginOn is more than just semantic.
I don't see any big advantage of
renaming _dummyLabel to dummyLabel
In some ObjC runtimes you have a hard time making instance variables invisible to users of the class. For them sticking some prefix (or suffix) on your instance variables can make it clear (or more clear) that you don't want anyone messing with your variables. However you don't want that gunk on your public functions. This lets you get it off.
It could also be useful if you need to maintain an old interface with one set of names at the same time as a new set of APIs with a new set of names (setLastname vs. setSurname).
Old post, but I think its important to mention, that it is recommended to access variables via getters and setters (so, with dot notation). Accessing a field directly (_ivar) is strongly recommended only when initializing it.
There is some good Apple's article:
https://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html
Last paragraph:
You should always access the instance variables directly from within
an initialization method because at the time a property is set, the
rest of the object may not yet be completely initialized. Even if you
don’t provide custom accessor methods or know of any side effects from
within your own class, a future subclass may very well override the
behavior.

self.variable and variable difference [duplicate]

This question already has answers here:
Difference between self.var and simply var
(3 answers)
Closed 8 years ago.
What is the difference between self.myVariable = obj; and myVariable = obj;, when I use #propery/#synthesize to create `myVariable?
It's important to note that dot-syntax is converted to a simple objc_msgSend call by the compiler: that is to say that underneath it acts exactly like a message send to the accessor for that variable. As such, all three of the following are equivalent:
self.myVariable = obj;
[self setMyVariable:obj];
objc_msgSend(self, #selector(setMyVariable:), obj);
Of course, this means that using dot-syntax actually results in a full message send, meaning calling a new function and all the overhead that is associated with it. In contrast, using simple assignment (myVariable = obj;) incurs none of this overhead, but of course it can only be used within the instance methods of the class in question.
The #synthesize directive tells the compiler to generate accessors for your member variables, according to the specifications given in the #property directive in your .h file. (I.e., if you specify retain, the setter will retain the variable, and if you specify copy, it will copy it.)
The accessors will (unless you specify otherwise) be named propertyName and setPropertyName.
Using the . notation (note, not the self syntax as stated above) is saying that you want to use the accessors (a good thing if you are setting strings, and want to ensure the retain count is correct, for example).
So, within your class implementation:
self.bill = fred will call the
accessor setBill.
bill = fred will set bill to fred
directly, without going through the
accessor.
One of the differences I found out when starting Cocoa development is if I set variable to use a #Property/#Synthesize syntax and I didn't use self.myVariable = obj or [self setMyVariable:obj] but instead myVariable = obj, the object is not retained if obj is released later. (Assuming #Property was set up to use retain.)
The reason is the retain count is not set when using myVariable = obj and when the obj is released the count is now zero. (Unless you retain it yourself) But by using the accessor it will do the retain count for you. (Again assuming you set it up to use retain when it was declared).
Shyne
If I can add one important note to this. The answer above are all awesome, so I won't add to the technical side. But just this:
If you create a synthesized property
#synthesize myProp;
Always use the self.myProp pattern to set it.
self.myProp = newVal;
This seems really obvious, but it's important. It's true that there is simply no reason to do this, but until you really understand how the synthesized setters are created you just want to assume you HAVE to use the self. pattern to set the value.
Honest: this will save you a lot of late night debug sessions. Non-retained memory access violations are simply the worst to debug.
The self syntax uses the accessor method, the other syntax does not. This might be a big difference if the accessor does something more than simply assign the new value. See the Declared Properties part of the Objective-C tutorial.
The other answers are correct, the difference is that the dot notation causes the ivar to be changed through the accessory rather than directly.
Until you know what you're doing, I recommend you use the dot notation (i.e. self.propertyName = ...). Cocoa/Obj-C does a lot with key-value coding, and while the phone SDK doesn't take full advantage of that (with things like bindings), eventually it will. Getting used to using the accessors now will save you a lot of headaches in the future.
Using the accessor methods also give you the opportunity to override them and provide more functionality should you need to. By simply changing the value of the ivar, you rob yourself of this capability.