Why is the "new" keyword not necessary in Swift? - swift

Why is the new keyword not necessary in Swift?
In other languages such as Java or C#, new is necessary to allocate memory for a each new object.
Ex.
(Foo) foo = new Foo()
However in swift, it's
(var) foo = Foo()
If Swift has built in garbage collection/memory allocation, is new implicit, or is it simply not used. If the latter, why/what replaces it?

new is just a language construct that says I want to initialize and create a new Foo. If the compiler is smart enough to determine that that's what you want to do from the context, why be verbose about it? The bottom line is that there's really no functional difference between:
[[Foo alloc] init] - Objective C
[Foo new] - Objective C
new Foo() - C/C++/Java
Foo() - Swift
Also note that in C++, you can use the following to generate a stack-based object:
Foo foo();
ARC, reference counting, garbage collection, explicit delete, are all just mechanisms for reclaiming memory used by objects that are no longer needed, and really have no bearing on the language syntax necessary to create an object in the first place.
Don't get hung up on syntax, learn to recognize constructs and operations, and then attach syntax to constructs and you're 90% of the way to knowing every programming language out there.

For heap-allocated/reference types (classes), Swift utilizes Automatic Reference Counting: rather than requiring explicit calls to delete, memory is deallocated when the last "strong" reference to it disappears. var foo = Foo() or let foo = Foo() allocates and initializes an instance of the Foo class, and creates a local variable with a strong reference to it. When this variable goes out of scope, if no other references have been made, the object is deallocated.
From The Swift Programming Language:
Every time you create a new instance of a class, ARC allocates a chunk of memory to store information about that instance. This memory holds information about the type of the instance, together with the values of any stored properties associated with that instance.
Additionally, when an instance is no longer needed, ARC frees up the memory used by that instance so that the memory can be used for other purposes instead. This ensures that class instances do not take up space in memory when they are no longer needed.
You can also read about the initialization sequence, i.e. the interactions between properties and custom inits in a class hierarchy.

Related

ARC doesn't apply to struct and enum, how are they deallocated in Swift

Since ARC doesn't apply to struct and enum, then how are they deallocated from the memory? I have to get stuck when it asked in the interviews and try to find the correct answer but can't find much info on it googling. I know swift is smart at handling value types. But how?
The memory management of objects (instances of classes) is relatively difficult, because objects can outlive a function call, the life of other objects, or even the life of the threads that allocated them. They're independent entities on the heap, that need book keeping to make sure they're freed once they're not needed (once they're no longer referenced from any other threads/objects, they're unreachable, thus can't possible be needed, so are safe to delete).
On the other hand, structs and enums just have their instances stored inline:
If they're declared as a global variable, they're stored in the program text.
If they're declared as a local variable, they're allocated on the stack (or in registers, but never mind that).
If they're allocated as a property of another object, they're just
stored directly inline within that object.
They're only ever deleted
by virtue of their containing context being deallocated, such as when
a function returns, or when an object is deallocated.

using boost::python::list as return value need increase ob_refcnt?

I am trying my best to find memory leaks in a very important module in our project and got a code snippet like this:
PyObject* python_func( const char* str )
{
..........................
boost::python::list obj;
obj.append(str);
obj.ptr()->ob_refcnt++; //this is necessary??
return obj.ptr();
}
I am confused about this line: obj.ptr()->ob_refcnt++;
I think ob_refcnt is maintained by python internally for gc, we can't operate it so obviously cause this will lead to memory leaks, on the other hand, obj is going to leave its scope, I am not sure if boost::python::list deconstructor will decrease ob_refcnt, if that's true, remove that line, the resource obj hold would be released, that will lead to a crash.
So my question is whether obj.ptr()->ob_refcnt++; is necessary, and why?
The reason the code increases the reference count is that python_func is intended to return a new reference to the object. (A new reference is one that has the reference count already increased -- returning a new reference allows the function to create new objects, such as a new list in this case.) On the other hand, the ptr() member function returns a borrowed reference to the object.
As you correctly surmised, if the code failed to increase the reference count of the borrowed reference, the destructor of boost::python::list would decrease the reference count and the returned object would be invalid.
Note that you should never directly access the ob_refcnt member of PyObject. The proper way to increase the reference count is through the use of the Py_INCREF macro or its boost::python equivalent boost::python::incref:
return boost::python::incref(obj.ptr());

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).

Objective-C properties - is using [self myProperty] or self.myProperty slower than myProperty?

I'm using Objective-C properties to handle retaining/releasing instance variables for me. In my class, i'm doing stuff like this:
self.myProperty = somethingIWantToRetain
[self.myProperty doSomeAction]
[self.myProperty doSomethingElse]
Is using [self myProperty] / self.myProperty slower than simply using myProperty for those lines where i'm not changing the value of myProperty? Eg would the following be faster?
self.myProperty = somethingIWantToRetain
[myProperty doSomeAction]
[myProperty doSomethingElse]
Thanks
It's almost certainly a little bit slower, but it's unlikely to matter much.
Referring to your ivar directly (with a naked myProperty) accesses the variable directly. Referring to your property getter (with the equivalent self.myProperty or [self myProperty]) has to invoke a method, which will generally perform a retain and autorelease on your ivar.
However, method dispatch in Objective-C is very, very fast, and the retain/autorelease calls are pretty cheap as well, especially for objects that will likely not be destroyed when the autorelease pool is cleared. I would focus on readability and consistent style, and only worry about performance here when it becomes clear that you have performance bottlenecks to chase.
To be precise, when you write [myProperty doSomeAction], you are not actually accessing the property, but accessing the instance variable (used as the backing variable of the property) directly.
You only access the property (thru its setter and getter) with the dot-notation [self.myProperty doSomeAction] (or by calling the setter/getter explicitly like [[self myProperty] doSomeAction] which is an exact equivalent, as this is what the compiler translates to when compiling your code)
So when you write [myProperty doSomeAction], as it access the variable directly — contrary to [self.myProperty doSomeAction] which calls the getter of myProperty thus making an additional method call / message send — then yes in theory it will be faster as you will gain one message dispatch.
But in practice you won't see any improvement, so there is no need to consider accessing the variable directly (and it will make you loose flexibility if you want to implement it another way later)
Moreover, if you use the Modern Runtime (which is the case if you code for any version of iOS, Legacy Runtime being only used in 32-bits Mac OSX), then explicitly defining the backing variable for the property is not needed anymore. Thus you can declare the #property in the .h and #synthesize it in the .m without any instance variable (the compiler will generate it for you at compile time), and in such case you won't be able to call the (non-existing) instance variable! (at least not before the #synthesize directive)
Using Objective-C 2.0 dot syntax is equivalent to calling the getter, so the first snippet would be slower on the basis that you'll incur two additional dynamic dispatches.
That being said, the loss will be minor and obviously you'll gain the flexibility of being able to change the setter and getter at a later date (such as if you end up making that value implicit such that it's not technically stored in memory, or passing it off to a third object, or doing something asynchronous to store that may require you to block on the getter in some circumstances).
Slower as in one more step in operation? Yes.
Slower as in noticeably or realistically slower? Absolutely not.
You have to remember that modern cpus run programs at several million operations per second. In virtually all languages, calling a getter method is essentially the same speed as accessing the ivar itself (especially when there's no other code in the getter method).
It's good habit to use getters rather than accessing the ivars directly though, so I wouldn't try to "speed things up" by ignoring them.
Yes, it would be marginally faster, but it's unlikely that you'll improve performance noticeably by doing this kind of micro optimization. If you use self.myProperty, you could later decide to implement a different accessor method without having to change your code everywhere.

Raw data types Vs Objects in Objective C

Something I've been wondering for a while. I know that in order to free up memory, objects (Such as NSMutableArray) have to be released, but raw data types (Such as int) don't. My question is, at what point does the space in memory that an int is occupying become free?
For example, a class "myClass" has an iVar "int a"
"a" holds the value some integer value.
When "myClass" is deallocated, does the space in memory that was holding the value for "a" become free straight away?
Thanks in advance.
For class ivars, the memory is freed when the object instance is deallocated - upon the last [release] call. For local int (and other primitive) variables, when the function returns. For global and static variables, when the process quits.
Also, you can allocate int's dynamically with malloc(). Then it's freed when you call free().
"a" is included in the memory allocated in "myClass". In other words, when myClass is deallocated, "a" is gone right along with it.
An Objective C object is similar to a pointer to a malloc'd C structure (containing both declared and a few hidden instance variables). When an object is released, the entire C structure memory block, including all internal ivar storage, is free'd (as well as any other dealloc housekeeping required).