Swift copy attribute in initializer - swift

How do I ensure objects passed to an initializer are copied, rather than only on setting those attributes later?
Using #NSCopying, Apple says we can achieve copy-property-like behavior. Per default, the attribute is only assigned though, without calling the setter which does the copying.
This is potentially dangerous as I want to rely on the property being immutable and not being modified without me knowing. (think of getting an NSMutableString instead of NSString - copying would give me an immutable instance).

Use #NSCopying while declaring the property.
From within the initialiser call self.propertyname = newValue, so that the setter gets called and copying is done.
To know when the value is being modified from outside of the class, implement the "set" observer (which also requires to implement get as well).

Related

When to use #property? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why should I use #properties?
When to use properties in objective C?
I have been programming in objective-c for a little over a year now, and I always felt like it was a convention to use #property and #synthesize. But what purpose do they really serve ? Are they solely there to be communicated between classes ? So, for instance, if I use an NSMutableDictionary only in the scope of the class where it was declared, an omission is O.K. ?
Another question:
If I set the property of an NSMutableDictionary, it is retained, right ? So, in my class I don't have to call alloc() and init(), do I ?
What are the rules to use properties ?
But what purpose do they really serve?
Access control to iVars and abstraction between representation and underlying data.
Are they solely there to be communicated between classes?
No, they are for when you want to control access to iVars instead of accessing them directly or when you could in the future change underlying data structures but wish to keep the current representation.
So, for instance, if I use an NSMutableDictionary only in the scope of the class where it was declared, an omission is O.K.?
It depends. Do you want to have controlled access to the iVar? Would it be possible for your code to change so the dictionary is fetched and not a direct iVar. Usually, the answer is yes.
If I set the property of an NSMutableDictionary, it is retained, right?
Depends on how you declare the property.
So, in my class I don't have to call alloc() and init(), do I?
You have sloppy wording here. I think you are asking if you still need to construct an instance of a property. Yes, you will need to construct an instance of a property in some way. There are lots of ways of doing this.
NOTE: the convention for talking about methods is use their signature. Instead of alloc(), you would use -alloc.
What are the rules to use properties?
This you will need to read the doc for.
Like in another languages, when we want to make our variable global or public we use public access modifier. In objective c when we want access our another class variable in other class, we use #property and #synthesize them. Basically #synthesize is way by which compiler create a setter and getter methods for that variable. You can manually create them but not use #synthesize.
By creating object of that class you can access your property variable in other class.
By using retain, you clear that is take place memory and not exist until that container class not goes dispose or released.
Properties simply make your life easier.
Nowadays use properties as much as you can in terms of memory management, code-style and timesaving.
What do #propertys do?
They can create getter and setter methods (depends on given parameters).
Normally you declare instance variables in the header file (like in c++).
Now you simply let that be and instead of that declare the properties you want for instance variables.
Properties can get multiple arguments.
For normal objective-c objects, where you need a pointer (*) you would write.
#property (nonatomic,retain,...)
When you #synthesize it it creates a getter and a setter.
The setter automatically does stuff like releasing your old object, that your variable hold and retaining the new one.
So you don't have to do that manually (which should be quite often the case). Thats important.
You also can give it arguments (readonly,readwrite) to decide if to set a setter or not.
You can even declare a #property in the header file readonly and override that in your implementation file with a extension (a category with no name).
To dive deeper into this, read the apple developer manuals, which are quite effective.
Hope that helps a bit.
Shure it is the tip of the iceberg, but it's mostly everything you need.

Why not use self. call inside class

I've read google's and apple's code guide, they both access instance variables without self. call(getter and setter) inside the method implementation even though they have declared a property for that instance variable.That's why?
In my opinion, using self. call to set and get instance variables inside the method implementation of class makes it easier to manager retain count.
Is there any caveat to use getter and setter inside class?
It depends. You should always use the accessor in normal use.
However for init and dealloc methods, you should instead use the direct ivars to release and set variables. That's because the setters can have side effects that are not good to trigger during class initialization or deallocation.
In practice using an accessor as part of init probably will not cause an issue. But I have seen a number of real world crashes where a custom setter was not expecting nil and so use of the accessor in dealloc crashed the app. Even if it didn't crash it could be doing a lot of pointless work since the class was about to die.

Why Use Properties?

So I've been programming on Objective-C for over a year now, and I can't seem to understand the use for properties. I have searched the internet a few times but never really found a good explaniation. I understand how to create them:
#property (something, something) something *variableName;
#syntheize variableName;
But should I make all my instance variables properties. To me, from what I know, it seems like a waste of code. But when I look at code online, sometimes I see like 25 properties in one class. Which I think is a waste. The only time I ever use them is when passing info from a UITableView cell selected to a detail viewController. For that, I use:
#property (copy) NSString *myString;
Can you also explain what: nonatomic, copy, retain, assign, etc. mean.
Thanks
These properties are convenience methods for creating getters and setters.
Atmoic v Nonatomic
Assuming that you are #synthesizing the method implementations, atomic vs. non-atomic changes the generated code. If you are writing your own setter/getters, atomic/nonatomic/retain/assign/copy are merely advisory.
With atomic, the synthesized setter/getter will ensure that a whole value is always returned from the getter or set by the setter, regardless of setter activity on any other thread. That is, if thread A is in the middle of the getter while thread B calls the setter, an actual viable value -- an autoreleased object, most likely -- will be returned to the caller in A.
In nonatomic, no such guarantees are made. Thus, nonatomic is considerably faster than atomic.
What atomic does not do is make any guarantees about thread safety. If thread A is calling the getter simultaneously with thread B and C calling the setter with different values, thread A may get any one of the three values returned -- the one prior to any setters being called or either of the values passed into the setters in B and C. Likewise, the object may end up with the value from B or C, no way to tell.
Ensuring data integrity -- one of the primary challenges of multi-threaded programming -- is achieved by other means.
Assign, retain, copy
In a nutshell, assign vs retain vs copy determines how the synthesized accessors interact with the Objective-C memory management scheme:
assign is the default and simply performs a variable assignment
retain specifies the new value should be sent -retain on assignment and the old value sent release
copy specifies the new value should be sent -copy on assignment and the old value sent release.
Remember that retain is done on the created object (it increases the reference count) whereas copy creates a new object. The difference, then, is whether you want to add another retain to the object or create an entirely new object.
Properties are a good technique to expose values. You shouldn't expose all instance variables as that would break good OOP encapsulation.
Here is Apple's documentation on the matter.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html
A key point is:
Declared properties address the problems with standard accessor
methods by providing the following features:
The property declaration provides a clear, explicit specification of
how the accessor methods behave.
The compiler can synthesize accessor methods for you, according to
the specification you provide in the declaration. This means you have
less code to write and maintain.
Properties are represented syntactically as identifiers and are
scoped, so the compiler can detect use of undeclared properties.
Properties enable automatic handling of the variables. So when you do a synthesize the compiler will generate your getters and setters allowing one to do class.variableName = value (indicating that the compiler will execute [class variableName:value].
Pretty decent explanation of the properties here: http://cocoacast.com/?q=node/103
If you need getters and setters to expose some instance variables, or you want some automatic retain/release memory management or thread safe accessors, then properties are a less verbose way to automatically create these smart getters and setters. If you don't want to expose something outside an object or thread, and don't want runtime memory management (say, for some malloc'd C struct) then properties might either a waste, or syntactic sugar (which may or may not improve code readability), or put there by a coder who doesn't know the difference.
The properties is a nice feature which gives you getter and setter method automatically by synthesize and give you relief by not setting and getting the value.
A property may be declared as "readonly", and may be provided with storage semantics such as "assign", "copy" or "retain". By default, properties are considered atomic, which results in a lock preventing multiple threads from accessing them at the same time. A property can be declared as "nonatomic", which removes this lock (reference from http://en.wikipedia.org/wiki/Objective-C#Properties).

What's the difference between self.propertyName vs. propertyName?

The title says everything!
In Objective-C, what's the difference between self.propertyName vs. propertyName?
self.propertyName is sending the object a message, asking it for the value of propertyName, which means it may go through a getter/setter, etc. propertyName is directly accessing the ivar, bypassing any getter/setter. Here's an article going into it in rather more detail.
self.propertyName increse the retain count by one if you have specified the propertyName as retain in property declaration
propertyName will not increase the retain count an could lead to the crash of application.
e. g. ,
#property (nonatomic,retain) NSString* propertyName;
lets say you have nameProperty NSString object.
Below increase the retain count by 1 and you could use self.propertyName and call release.
self.propertyName = nameProperty;
[nameProperty release];
Below does'nt increase the retain count so if you use propertyName in your application it will result in crashing of your application.
propertyName = nameProperty;
[nameProperty release];
Any further use of propertyName will result in crash.
self. runs through your likely synthesized accessor methods if you are using properties
ie self.propertyName = newName is the same as [self setPropertyName:newName]
This becomes important for memory management as propertyName = newName would cause you to loose reference to the previous contents of propertyName
If you call self, you can be sure you're calling the class/object that owns the property.
You may find this useful too:
Assigning to self in Objective-C
dot notation is turned into a method call by the compiler. This means that there is extra work at run time for executing this method call, like copying something from and to the stack memory and executing a jump in machine code.
the instance variable by itself is faster because it is essentially just a memory address or scalar value (like int).
One would prefer the self.something notation when you want or need an extra layer to do something. Like retain an object that is passed in or lazily instantiate an object on the first time you need it.
Setting the value of the property does just that - it sets the value of the property directly without going through any accessors or synthesized accessors.
By calling the accessor through self you are going through the accessors. For properties that have been declared with retain or copy it will retain or copy the value that is passed in. For non objecte properties, the usual declaration is assign which means that there is no memory management applied to those iVars.
You see both types of calls - but it is preferred to use the direct method in initialisers and the dealloc method, because calls to self are discouraged in these methods.
If you have declared and synthesized the property, the call to self also generates the KVO notifications for changes in that variable. This saves you having to write the willChangeValueForKey: and didChangeValueForKey: methods.

Couldn't I just pass an copied string to an Core Data property?

The docs say:
The default implementation does not
copy attribute values. If the
attribute value may be mutable and
implements the NSCopying protocol (as
is the case with NSString, for
example), you can copy the value in a
custom accessor to help preserve
encapsulation (for example, in the
case where an instance of
NSMutableString is passed as a value).
So instead of getting into trouble and inconvenience with overwriting accessors in my NSManagedObject subclass, couldn't I simply do something like this?
myManagedObject.firstName = [[firstNameMutableStr copy] autorelease];
This would have the exact same effect, or not? The dynamic implementation would retain that anyways ... so.... why not the easy way?
It's an open question whether having to remember to copy the mutable string every where in code you set the attribute is "the easy way."
With a custom accessor, you just write the copy once then forget about. It copies automatically from that point on.
Just imagine that in thousands of lines of code you forgot to copy just once and developed a subtle bug because that one attribute of the managed object sporadically changed because some other totally unrelated code subsequently changed the mutable string you held only by reference.
I could tell you some stories of weekends lost to debugging because someone took "the easy way."