Difference between self.view.addSubview and view.addSubview - ios

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

Related

Adding properties in Objective-C category

Is it recommended to add properties in categories to an Objective-C class? Is there an official Apple link?
First of all I want to say that Peter Segerblom's answer is not correct. But maybe Daji-Djan's comment is misleading.
From the very beginning:
A declared-property is solely a declaration of two (one – for readonly properties) methods. Period.
This means that it is a declaration.
This means that it refers to methods.
Therefore you can add declared-properties in a category.
But if the property is explicitly or implicitly (Apple: automatically) synthesized, it will synthesize an ivar, if there is none. This is impossible, because it would change the memory footprint of instance objects and a point in time, instance objects are already allocated.
So you have to do one of the things below:
Already having an ivar. (What makes it a bit meaningless.)
No synthesization of the declared-property.
However, this can be useful for computed properties, for properties, whose values are stored in another object, for properties, whose values are stored as associated object, for …
You can do this with associated objects. Although this is not recommended. This link has everything you need to know.
http://nshipster.com/associated-objects/
Section out of the blog:
Associated objects should be seen as a method of last resort, rather than a solution in search of a problem (and really, categories themselves really shouldn't be at the top of the toolchain to begin with).
You can easily do that -- if apple does this, I don't know. They often expose properties in categories though..
anyway, if it makes sense for your design, go ahead! Remember though that while you can add properties, you can't add variables to existing classes.
so either have computed properties, that are a kind of 'convenience wrapper' around existing functionality OR add variables using associated storage
You can't add properties to categories. I think this has something to do with the way memory is handled. Adding instance variables to a already existing object would change the size of the object.

Casting method parameters in Objective-C

Update
Okay, first of all, thank you all for the huge amount of activity. It seems that I did not phrase my question too well, since many of the answers got (rightfully) stuck on the id input parameter, and following poor design patterns, but it was merely an example. I'll add some context to my question:
Suppose that there are multiple different implementations for doSomethingWithParameter:, requiring a specific instance as input parameter
My class in the example will only ever get called with an instance of SpecificClass as input parameter
With these assertions, here is my assumption: Given, that you know the type of the parameter, there is no benefit in type checking and casting, just for the sake of extra safety.
Original post
Suppose I have a general method in my protocol declaration, which takes an id input parameter:
#protocol MyProtocol <NSObject>
- (void)doSomethingWithParameter:(id)inputParameter;
#end
In a class, which conforms to MyProtocol, I usually prefer making the type of inputParameter explicit like so:
- (void)doSomethingWithParameter:(SpecificClass *)inputParameter
{
/... do something with param
}
Occasionally I received critique for choosing this solution, as opposed to the following:
- (void)doSomethingWithParameter:(id)inputParameter
{
if ([inputParameter isKindOfClass:[SpecificClass class]]) {
SpecificClass *myInstance = (SpecificClass *)inputParameter;
/... do something with param
}
}
I really prefer the first version, since it clearly states the parameter my instance is expecting. It is more concise, and clear. I generally don't think I can gain much from type checking/casting.
My question: from a coding standard standpoint, which one is the better solution? Does the first one have any disadvantages?
Update
From the update to your question, it seems that you are trying to achieve some variation of a functionality provided by the generics in modern languages.
Since Objective-C does not support this pattern, you can either sacrifice type safety, or rethink your design decisions.
If you go the first way, you should make it really clear by other means (naming, documentation) what types are you expecting. Then it might be reasonable to assume that your method will only be called with proper params.
But I would still add NSParameterAssert to simplify future debugging.
Original Answer
If you are using the first approach, you have a mismatch between declaration and definition of the method. Due to dynamic nature of obj-c (method signature does not include types of parameters), compiler does not complain about it.
However, when calling the method, only declaration is visible, so any information about the type of parameters is derived from that - all the type checking (yes, here compiler does it) is performed based on declaration.
In conclusion, to avoid confusing bugs and misuse of API, you should definitely use the second approach. Or change declaration together with definition.
Edit
Also, I can think of third solution, that somewhat merges convenience of the first approach with type safety of the second one:
- (void)doSomethingWithParameter:(SpecificClass *)inputParameter
{
NSParameterAssert([inputParameter isKindOfClass:[SpecificClass class]]);
// do something
}
First of all, when you use id for a parameter type that means either that type may vary or you may invoke method with ambiguous parameter. For both cases, second one is preferred as it checks type and prevents unwanted crash.
If you prefer the type of inputParameter explicit then simply define it in the protocol, like
#protocol MyProtocol <NSObject>
- (void)doSomethingWithParameter:(SpecificClass *)inputParameter;
#end
and for this forward declaration you may have to import module/class, like
#import "SpecificClass.h" // import class
OR
#class SpecificClass; // import module
What you do is perfectly fine. If your method is called with a parameter that is an instance of the wrong class, that is a bug in the caller. In Objective-C, you don't work around bugs, you make them crash your code, and then you fix the bug (that is why nobody handles exceptions, exceptions are bugs in your code and when they crash your code, the cause of the exception needs to be fixed).
This is much more common when you pass blocks, for example a block testing array elements, where you know exactly what type of array to expect.

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