should I avoid using new to initialize my objects? [duplicate] - ios

This question already has answers here:
Use of alloc init instead of new
(8 answers)
Closed 9 years ago.
Recently i was told Apple is discouraging the use of new, and google's iOS coding standards also has this to say:
Do not invoke the NSObject class method new, nor override it in a subclass. Instead, use alloc and init methods to instantiate retained objects.
Modern Objective-C code explicitly calls alloc and an init method to create and retain an object. As the new class method is rarely used, it makes reviewing code for correct memory management more difficult.
Why would it make reviewing code for correct memory management more difficult though?

I expect the reference to ease of code reviews merely meant that human readers of your code may not notice the word 'new' as their eyes scan over the code looking for alloc-init calls.
In Objective-C, the word 'new' is a shortcut for calling alloc and init. But then you cannot pass arguments; you are calling the no-arg constructor. If you later change your code in such a way that you now want to call one of the other constructors and pass arguments, you will need to change your "new" to an alloc-init. This is common enough that it is yet anothe reason to avoid calling 'new' in the first place.
There is no advantage to calling 'new' over calling alloc-init. The 'new' word is only in Objective-C because other languages such as Java use that keyword.

Related

Difference between self.view.addSubview and view.addSubview

I have done a bunch of coding in swift and prefer to do a lot programmatically and I was wondering what the difference was between these two:
self.view.addSubview(someNewView)
view.addSubview(someNewView)
they both seem to work. Is one better for some reason? Are they actually that different?
If this is a dumb question or already answered it can be removed. Just a thought.
There's no real difference, although you may see the use of self more often from previously Objective-C developers. From the docs:
In practice, you don’t need to write self in your code very often. If
you don’t explicitly write self, Swift assumes that you are referring
to a property or method of the current instance whenever you use a
known property or method name within a method.
...
The main exception to this rule occurs when a parameter name for an instance method has the same name as a property of that instance. In this situation, the parameter name takes precedence, and it becomes necessary to refer to the property in a more qualified way.
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Methods.html

With the Objective-C/Swift Singleton model, why do we create a shared instance and not just use class methods? [duplicate]

This question already has answers here:
Objective-C: Use singleton vs. use class as an object?
(3 answers)
Closed 8 years ago.
It seems we always use a sharedInstance class variable to access the Singleton and perform methods on it. But why don't we just make all operations class methods and not have a variable to deal with at all? [SingletonClass uploadFile:(NSFile *)file] instead of [[SingletonClass sharedInstance] uploadFile:(NSFile *)file] (or the Swift equivalent).
What benefits do the variable bring? Or am I just overlooking some very integral concept in Singletons that not having a variable would prevent?
Furthermore, what stops this variable from being deallocated by memory? I know it's only created once, but why doesn't it ever get removed?
You create a shared instance if you need to be able to store state. If you can get away with just class methods, that is definitely preferable. The less state you have in your app, especially with singletons, the fewer bugs you will create.

Why do we needed category when we can use a subclass? and Why we needed blocks when we can use functions?

These two questions are quite common when we search it but yet I need to get a satisfying answer about both.When ever we search a difference between say subclass and a category we actually get definition of both not the difference.I went to an interview to a very good MNC working on iOS and I was encountered with these two questions and I gave almost all the answers I have read here but the interviewer was not satisfied.He stuck to his questions and was that-
Why do we needed category when we can use a subclass?
Why we needed blocks when we can use functions?
So please explain me what specific qualities blocks and category add in objective C that their counter part can't do.
First...
Just reading the documentation "Subclassing Notes" for NSString shows why creating categories is sometimes better than subclassing.
If you wanted to add a function -(void)reverseString (for instance) to NSString then subclassing it is going to be a massive pain in comparison to categories.
Second...
Blocks are useful for capturing scope and context. They can also be passed around. So you can pass a block into an asynchronous call which then may be passed elsewhere. TBH you don't care where the block is passed or where it is finally called from. The scope captured at the time of creating the block is captured too.
Yes, you can use methods too. But they both have different uses.
Your questions are a bit odd. It's like asking...
Why do hammers exist when we can just use wrenches?
You can't use subclassing when someone else is creating the objects. For instance, NSString is returned from hundreds of system APIs, and you can't change them to return MyImprovedString.
Functions split up the logic; blocks allow you to write it closer together. Like:
[thing doSomethingAndWhenFinishedDo: ^{ some_other_thing; }];
the same code written with functions would put the second part of the logic several lines away in the file. If you have a few nested scopes in your logic then blocks can really clean it up.
Why do we needed category when we can use a subclass?
Categories let you expand the API of existing classes without changing their type. Subclassing does the same thing but introduces a new type. Additionally subclassing lets you add state.
Why we needed blocks when we can use functions?
Block objects are a C-level syntactic and runtime feature. They are similar to standard C functions, but in addition to executable code they may also contain variable bindings to automatic (stack) or managed (heap) memory. A block can therefore maintain a set of state (data) that it can use to impact behavior when executed.
You can use blocks to compose function expressions that can be passed to API, optionally stored, and used by multiple threads. Blocks are particularly useful as a callback because the block carries both the code to be executed on callback and the data needed during that execution
Category : It is used if we want to add any method on a given class whose source is not known. This is basically used when we want to alter the behaviour of any Class.
For example : If we want to add a method on NSString to reverse a string we can go for categories.
Subclassing : If we want to modify state as well as behaviour of any class or override any methods to alter the behaviour of the parent class then we go for subclassing.
For example : We subclass UIView to alter its state and behaviour in our iOS code.
Reference :
When to use categories and when to use subclassing?
What is the difference between inheritance and Categories in Objective-C
We need new method but we don't need new class so we need category.
We need function but we don't need named function so we need block.

Why I should access the instance variable directly from within an initialization method?

The Apple Programming with Objective-C document states that:
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.
But I don't know what side effects will be in a setter method, please give me a example to explain why I have to access the instance variable directly from within an initialization method
The answer is simple - it is code smell. Dot notation like self.foobar = something in Objective-C is just a syntactic sugar for messaging.
Sending messages to self is normally fine. But there are two cases you need to avoid them:
1. When the object is being created, and
2. When the object is being destroyed.
At these two times, the object is in a strange in-between state. It lacks integrity. Calling methods during these times is a code smell because every method should maintain invariants as it operates on the object.
If a setter method is overridden by a subclass, you have no guarantee that your instance variable will contain the correct data. If you want to maintain data integrity within your objects during a crucial phase such as initialization, you should do as Apple recommends.
In addition to #JacobRelkin point, side effects can include Key-Value Observing. Other objects can observe changes even during -init* and -dealloc. I've had a KVO -dealloc bug in the past.
It truly is a best practice to setup and tear down the ivars directly.

IOS: When declaring properties in a .h what's the difference between self.var and just var? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Objective-C - When to use 'self'
I needed a variable to be passed from one view to another so I made a property called StringC in the .h and accessed it using self.StringC (that part worked).
I also need some arrays that are accessible throughout the view but I'm using them differently.
For instance I have lvLabelArray and I'm using
self.lvLabelArray=[[NSMutableArray alloc]init];
and then later I'm using
[lvLabelArray addObject:LabelText];
Is there a difference between that and
[self.lvLabelArray addObject:LabelText];
?
Sorry I don't know the terms for those kinds of variables.
There is an important difference there.
self.attribute goes through the object's getter or setter function, as appropriate. That allows you to set up initial values, trigger update messages, or anything else.
Accessing "attribute" directly goes straight to the underlying variable, so you bypass all that. As a result, it's definitely the less-preferable way of working.
A common way of avoiding this confusion, and just plain mistakes, is to rename the underlying variable. Instead of just "#synthesize attribute", use "#synthesize attribute = _attribute". This will create the getter and setter methods as before, but they'll the underlying variable is named "_attribute". That means that trying to use "attribute" without "self" will trigger a compiler error.

Resources