difference between public ivar and private proprety in objective c - objective-c

May I know what is the difference between instance variable in .h file and property in .m file in objective c?
I know that both cannot be used outside the class. Any other difference?

A. You can add ivars inside the implementation, too:
#implementation AClass
{
id ivar;
}
Therefore the difference is not that ivars has to be in the header (interface). (But see below B.)
B. If an ivar should not be used outside, there is no reason to put it in the public header. Why do you want to inform somebody about an ivar, if he cannot use it? This is source code spamming.
C. A property adds (or uses) an ivar. Additionally it adds accessor methods.
D. A property provides additional semantic information, especially about atomicity and setter semantics, if it is declared in the header.
Up to here it should be clear that properties are usually the better way to model an object state. So why do we have ivars in headers?
This is for legacy. In former times we did not have declared properties. There has been some reasons for having ivars in the header (for example to tell the compiler the object size), but this are gone. The only meaning for declaring ivars in the header in nowadays is that you make them public and let others access them directly for performance reasons. You should have very good performance reasons to do so. I had never had them.
In addition to Jef's answer:
If you want to make ivars public to subclasses, you can put them into a class continuation in an extra file. Let's have an example:
MyClass.h
// We do not put ivars in the public header. This is an implementation detail.
#interface MyClass : NSObject
…
#end
MyClass_SubclassAddition
// We do put ivars in an extra header with a class continuation, to make them visible for subclasses
#interface MyClass()
{
id ivar;
}
#end
MyClass.m or MySubclass.m
// We use both headers in the implementation and subclass implementation:
#import "MyClass.h"
#import "MyClass_SubclassAddition.h
#implementation MyClass
…
#end
You can get rid of the "subclass ivar problem", if you use setters in initializers. Whether this is wrong or not to do so, is a different discussion. Personally I prefer to use setters. But do not let us start that discussion again (and again and again …)

the biggest practical difference is that subclasses can see and use ivars which are declared in the .h, where if they are in an extension at top of the implementation file a subclass cannot access them.
I like to start with them in the .m file but i'll happily move one to the header in order to use it from a subclass.

Related

Is following use of objc #protected directive safe/legit?

I have to expose a private property to sub-classes.
Since there is no such thing as "protected properties" in objc AFAIK, I'm using the #protected directive to expose the corresponding ivar that's synthesised by the complier.
This method appears to work, however, I'm not sure if I'm affecting the synthesis of the property and ARC in some inadvisable way?
I'm using a weak property here to show how the compiler forced me to use __weak modifier with the #protected directive, i.e. it appears the complier is aware of the two declarations and the link between them.
Superclass .h file
#interface Superclass : NSObject
{
#protected
SCNScene * __weak _scnScene;
}
#end
Superclass .m file
#interface Superclass ()
#property (weak, nonatomic) SCNScene * scnScene;
#end
#implementation Superclass
........
#end
Subclass .m file
#implementation Subclass
// Can use _scnScene just fine
_scnScene = .....
#end
Yes, it'll probably work. Don't do it this way. It's very inflexible. It forces you to declare ivars in the header, it only works with ivars, and it doesn't give you any control over read/write controls (or let you create a custom getters/setters). There isn't really a good reason to use the # access controls anymore (not since the move to non-fragile ivars, and they weren't that useful before).
A typical way to do this is with a +Protected header with a category. For example, you'd create a header file Superclass+Protected.h like this:
#interface Superclass (Protected)
#property (weak, nonatomic) SCNScene * scnScene;
#end
Then you import that into any implementation files that are allowed to access scnScene. Note that you could make this readonly if you wanted, so internally it's writable, but to protected implementations it's only readable, and to the public, it's invisible.
This is more flexible than literal "protected" because you can import this header into any other implementation where it is appropriate. So it can also be the equivalent of C++'s "friend." Obviously naming the file and providing some header comments can be helpful to let callers know if they should or shouldn't import this file.
To any complaints that this doesn't enforce access controls (not that you made any, but for anyone that does), neither does #protected. If I call valueForKeyPath:, I can access protected ivars, too. ObjC helps you create "no trespassing signs" so that callers know when they're in places they shouldn't be. It doesn't try to stop programs from accessing their own memory space. (This would be a futile goal; you can always read private variables and call private functions in any language that allows raw memory access; the point of access controls is to help callers write correct code, not stop them from doing anything.)
In the context of a class declaration, protected is the default visibility for instance variables, so your declaration has no effect. In fact, the following declaration:
#interface Superclass : NSObject
#end
would have the precisely the same effect as the declaration you posted, because the compiler automatically synthesizes any needed ivars for declared properties, unless you declare them yourself.

Objective-C #interface and #implementation clarification

I'm still fairly new to Objective-C but I'd love to learn more about how it should be done.
I'm building a simple cheat sheet that I'd like to print and put on my office wall as a reminder.
Here's what I have so far:
// Headers (.h)
// Shows what's available to other classes
#interface ExampleViewController : UIViewController
// Declare public methods, ivars &
// properties that are synthesized.
#end
// Implementation (.m)
// Defines the content of the class
#interface ExampleViewController ()
// Class extension allowing to declare
// private methods, ivars & properties that are synthesized.
#end
#implementation ExampleViewController
// Private Properties
// Method definitions
#end
One thing I don't understand is why have both #interface and #implementation inside the implementation .m file?
I get that we can declare private stuff but why not simply throw them in #implementation like:
#implementation ExampleViewController
UIView *view; // private property
- (void)...more code
#end
#1 - Why should I ever use #interface from within my implementation .m file?
#2 - For header .h, why should I ever use #class more than #import?
#import actually gets the whole definition and #class tells the compiler that the symbol is a class. So I just don't see why I should ever use #class?
#3 - Otherwise, is there anything I should be adding somewhere in my .h or .m cheat sheet?
That's not a problem-related question but a more wiki-esque question so we everybody can look it up and completely and quickly understand those concepts as they are very hard to grasp for any newcomer.
Why should I ever use #interface from within my implementation .m file?
Because it's better to clearly separate public and private parts of the class.
For header .h, why should I ever use #class more than #import?
When forward-declaring classes for use in protocols. Like this:
#class Foo;
#protocol FooDelegate
// this wouldn't compile without a forward declaration of `Foo'
- (void)fooDidFinishAction:(Foo *)f;
#end
Otherwise, is there anything I should be adding somewhere in my .h or .m cheat sheet?
That's way too general to be answered in one post.
1 - Why should I ever use #interface from within my implementation .m file?
When you do not intend to expose that interface to any other component. That's certainly the case for private class extensions but may also apply for something like a test which doesn't need a .h file at all because while it does define a class it does not need to expose an interface for any other component to use.
2 - For header .h, why should I ever use #class more than #import?
Invert your question; why should I ever use #import rather than #class?
#class informs the compiler that a class definition of that name will exist to be linked but says nothing about it's interface.
#import makes the class' interface available to you.
A forward declaration requires less work and can allow for faster builds. It is also not always possible to #import a class at all times (as in circular references like #H2CO3's protocol example). If all you need to know is that a class exists then just use the forward declaration. When you actually need to interact with its specific interface (usually in your class' implementation) then you need to #import.
3 - Otherwise, is there anything I should be adding somewhere in my .h or .m cheat sheet?
Unless you intend to actually expose ivars as a public interface (almost certainly not the case) leave them out of your .h and expose only properties instead.
Keep your public interface as simple as possible. Try not to reveal implementation details. However keep it informative enough that users of the class can verify its behavior using that public interface. (I find test driving the design of the class using only it's public interface a good tool for striking this balance.)
Imports and forward declarations expose dependencies. Keep them to the minimum you actually need so that you can understand what the class in question actually depends on.
Delegate protocols and block types are a common part of a class' interface but not part of the #interface. Include them in the .h if they are needed by other classes (e.g. to register callbacks).

Is modern Objective-C convention really to not have any ivars that aren't properties? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
iOS: must every iVar really be property?
I just read a book that said that modern convention is not to declare any ivars at all in your .h file between curly braces, and instead to make everything properties.
I want to make sure this is true even in trivial cases. I am making a class where there is a BOOL named "recording" which says whether the device is currently recording some video. This isn't something that other classes need, and my incline is to just put it as a BOOL in the header then refer to it in the .m file in the 2 spots where it is needed.
However, I also want to do things the accepted, right way. But I don't see why I make it a public property?
What you read is wrong, plain and simple.
Modern convention is to skip ivars when there is a corresponding property that can synthesize them. Additionally, with recent versions of LLVM it is possible to move your ivars to your implementation file (as #DrummerB has already mentioned) so that the header contains no ivars. That's considered good practice because it doesn't expose internal workings of the class.
But have no ivars at all and a property for everything that was an ivar? Nope, not normal Objective-C.
Your book is right (and wrong). Don't declare ivars in your headers anymore. That's only supported for compatibility reasons. But also don't declare properties for private variables.
If you want do declare a private ivar that other classes don't need to use, declare them in your implementation file:
// MyClass.m
#implementation {
BOOL recording;
}
// methods
#end
I recommend to not use ivar at all. Instead you can create a class extension in which you will declare properties that has to be hidden:
#interface MyClass ()
#property (nonatomic, assign) BOOL recording;
#end
You could use something like
#interface G4AppDelegate ()
#property (nonatomic, assign) BOOL recording;
#end
To make an "internal" property.
Or as the other answer states use an iVar in your implementation
Some books explain that you should only use getter and setter to access your ivar, even if they are private. This is a little too psychotique to me.
Before clang, u should have to create category on class and use synthesizer to make ur ivar private. like this:
#interface AppDelegate ()
#property(nonatomic, assign)int aValue;
#end
// + #implement AppDelegate
// #synthetise aValue;
that could be annoying since sometime u need some simple ivar, without any getter/setter control. And u're adding code where there is no need.
Now with clang you can put ur ivar directly on implementation file like this in ur code:
#interface AppDelegate (){
int _aValue;
}
#end
And u're hiding private ivar out of the scope the header.
Note, u can't compile this with gcc.

What's the difference between adding pseudo-private ivars in a class extension or in the #implementation block?

What's the difference between putting pseudo-private instance variables in a class extension inside the .m file, or putting them in the newly introduced #implementation brackets like shown below?
Are there consequences, pros, cons over one or the other way? Is internal2 treated differently than internal3 in a way a programmer must care of? (of course there is a difference McKay would say but the question is if you care in practice or not).
// MyClass.m
#interface MyClass () {
id internal2;
}
#end
#implementation MyClass {
id internal3;
}
- (void)internalMethod {
NSLog(#"%# %#", internal2, internal3);
}
#end
source: http://www.mcubedsw.com/blog/index.php/site/comments/new_objective-c_features/
The main difference between the two approaches is that you can include the class extension in a separate header, whereas the #implementation ivars obviously have to go with the #implementation block in the .m file (and there can only be one #implementation for a given class (extensions not included)). The practical result of this is that you can have multiple levels of "private" ivars:
MyClass.h: public ivars
MyClass+Private.h: semi-private ivars
MyClass.m: really private ivars
As a hypothetical example, pretend that MyClass is UIView. In that case, UIView.h is the header that we can all access, UIView+Private.h is the "private" header than only Apple can access, and UIView.m has stuff that only the people specifically responsible for UIView need to know about.
Personally, I prefer to put my ivars in a single class extension in the implementation file, I think it's cleaner that way. I don't think there are any performance advantages or consequences to using one or the other, it's more about being able to code the way you want to.

public objects and use of property

I'm a bit confused; if an object is declared in the .h file it is considered automatically as "public" right? We use a #property in the .h file, however, to edit them? This is where I don't understand: we use the getter/setter for private objects, so why do we use the #property for objects declared in the .h file and thus considered as "public"?
Second thing, I found this example: I don't understand why we use a #synthesize for primaryKey in this code: http://staging.icodeblog.com/wp-content/uploads/2008/08/9-todom1.png
and why we don't use a #property for the database object?
It is not correct that if an object (ivar) is declared in a .h file, then it is public. It is only if getter/setter methods are provided, otherwise it is not.
Indeed, the #property/#synthesize directives are facilities meant to declare and define default getter/setter methods. So, instead of writing them yourself, you just use the directives.
It is also worth noting that declaring properties you get the possibility of using the dot notation to refer properties of your objects. And also that they clarify a lot, thanks to the retain/assign/copy specifiers, how memory is meant to be managed for that properties. (And, of course, #synthesize will just do that correctly for you).
About your sample, in fact, whether an ivar is associated to a property or not is a design choice. Possibly, you just reconsider the assumption that ivars declared in .h files are public by defaults, and it will become clearer. In other words: primaryKey is public, database is not.
A very nice tutorial can be found here but also do not forget Apple docs.
EDIT:
about your question from the comment section:
it is not necessary that every ivar has a property, nor that it has getter/setter in order to be used inside of that class implementation.
#interface SomeClass : NSObject {
AnotherClass* _anotherClassObj;
AThirdClass* _aThirdClassObj;
}
#property (nonatomic, retain) AnotherClass* anotherClassObj;
#end
So, here you have two ivars; only one has got a #property declaration. In your .m file you may have, e.g.
#implementation SomeClass;
#synthesize anotherClassObj = _anotherClassObj;
- (void)initWithClasses:(AnotherClass*)obj1 and:(AThirdClass*)obj2 {
.....
self.anotherClassObj = obj1;
_aThirdClassObj = obj2;
...
}
....
#end
In this code:
#synthesize will provide implementation for getter/setter for anotherClassObj so you can use syntax: self.anotherClassObj = obj1; that syntax can be used equally from inside and outside the class implementation;
when you have no getter/setter (either auto-generated or custom) you can assign directly to an ivar by using the syntax _aThirdClassObj = obj2;, with the semantics of simple pointer copy; anyway, _aThirdClassObj will not accessible from outside that class;
furthermore, #property ... anotherClassObj notwithstanding, you can still refer _anotherClassObj directly in your .m file, like in _anotherClassObj = xxx, bypassing getter/setter, if you ever need it.
One thing you should have clear is that getter/setter are not only a way to make an ivar "public". They also play an important role in managing the retain count (depending on which specifier you choose among retain/assign/copy in the property declaration). So, in self.anotherClassObj = obj1; above, obj1 is assigned to _anotherClassObj and it is also retained (and if _anotherClassObj was previously pointing to an object, that object will be sent a release). Raw ivar assignment does not provide that kind of facility.
In my opinion, the retain count management feature of properties is far more important than visibility for deciding whether I use a property or not.
Not everything in the header is public, by default ivars (items in the { }) are #protected. The purpose of the #property is data encapsulation. #synthesize or #dynamic is used for declaring the way you want to implement your property and one or the other is necessary to prevent crashes and warnings.
Resources:
Defining Classes #protected, #package, #private, #public reference
Declared Properties #property reference