Objective-C: what is private what is not? - objective-c

Why are people using
#interface ViewController : UIViewController
{
#private
UIButton* button_;
}
#private declarations in public headers? Declaring a variable inside an implementation yields the same result, doesn't it? It feels strange to me, I thought a public header should only contain really public members. What to do with protected members?
#implementation ViewController
UIButton* button_;
#end
The only difference I know of is that this variable is only visible inside the current compilation unit (the .m file, right?)
Does the same hold true for methods? I could compile fine with proper method ordering or forward declarations. Why do people care to declare categories for private methods? For testing purposes only?

The variable declaration inside the #implementation block will create a global variable, and not an instance variable. Instance variables need to be defined as part of the #interface.
While you can create an additional #interface block, by means of a category or extension, but it can only contain method declarations, and not instance variables.

I would say that while it might "feel" wrong to you to put private instance variables in a supposedly public header, I wouldn't worry about it.
Take a look at pretty much any header file for a Cocoa class (except for the cluster classes), and you'll see that Apple declares their instance variables in their public header files.
Since Apple is OK with it, I don't think you have much to worry about. =)
FYI: All instance variables are protected by default.

Does the same hold true for methods?
No, methods are visible to any part of the program. If you know the selector you can callit.
I could compile fine with proper method ordering or forward declarations. Why do people care to declare categories for private methods? For testing purposes only?
Private categories are a form of forward declaration. You can think of them as if they were C prototypes.
Andrew

#private is referring only to the iVars.
By default you can access ivars of an instance like so:- id iShouldNotDoThis = foo->bar;
#private means you can't access the ivar like that and have to use the access methods.
id thisIsBetter = [foo bar];
Nothing to do with private categories or methods.

Related

How to access protected variable in Objective-C?

I know protected variable can't be access out side the class but is it possible to access them in Category or in SubClass, I think it's not possible for Subclass but is it the same case for Category ?
What I want to do is some modification to a library form github but I don't want to modify the original source code. I want to achieve this through subclassing or using category but the problem is I want reference to some protected variable.
Protected variable in .m file:-
#interface Someclass() {
NSMutableDictionary *viewControllers;
__weak UIViewController *rootViewController;
UIPageViewController *pageController;
}
#end
A category cannot access private instance variables nor can a subclass do that.
As you have access to the source code and just don't want to change the original source code you could create another class with exactly the same data structure. (same variable names and types declared exactly in the same way and sequence).
#interface Shadowclass() {
NSMutableDictionary *viewControllers;
__weak UIViewController *rootViewController;
UIPageViewController *pageController;
}
#end
Then add getters and setters to Shadowclass to make the values accessible.
The do:
Someclass *someclass = ... // you get the object from somewhere somehow.
object_setClass(someClass, [ShadowClass class]);
How someclass is of the type ShadowClass and you can access the getter and setter. Frankly I am not sure how the current compiler allows for accessing the getters directly of if you are allowed to cast someClass now an ShadowClass type object variable, but you can use performSelector for accessing the getters or setters.
Accessability of getters and setters directly like [shadowClass rootViewController:xxx] may even vary whether you are using ARC or not. (The compiler's behaviour here may even be configurable. This, too, I do not know on detail out of the top of my head.)
However, I am not sure whether I really want to recommend that! You may find less "hacky" alternatives.
And do not underestimate the importance of creating exactly the same structure for Shadowclass as for Someclass!

difference between public ivar and private proprety in 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.

Variable in implementation file

I just started picking up objective c and I have been following a tutorial online.
In the tutorial, it set the NSMutableAray pointer in the implementation (.m file) in the curly brackets.
I thought the pointer variable should be declared in the header file.
What is the reason / benefit of having the pointer variable in the implementation file in the curly brackets?
#interface AppDelegate ()
#end
#implementation AppDelegate
{
NSMutableArray *_players;
}
Two reasons for declaring instance variables in the #implementation:
The instance variable is private to the implementation, it is implicitly private, cannot be made public, and no even subclasses can see it. This restricts access from outside the implementation to the value of the instance variable, or to setting its value, to public (or protected) methods/properties declared in the interface.
It de-clutters the public #interface by removing details which are not relevant to the user of the class, but only to its implementation.
Originally Objective-C did not support declaring instance variable in the #implementation, but it has for a few versions of Xcode/clang by now. In old code you will still see instance variables in the #interface, but it is better in new code to declared them in the #implementation.
HTH
Apparently so private interface is unavailable outside

why to declare some instance variables as properties

Though this is somewhat a very basic question but I have some doubts still left after reading so many documents and questions on stackoverflow.com.
I want to know why to declare some instance variables as properties.
MYViewController.h
#interface MyViewController : UIViewController {
UIButton *btn;
NSString *name;
}
#property (nonatomic, retain) UIButton *btn;
#property (nonatomic, retain) NSString *name;
MyViewController.m
#implementation MyViewController
#synthesize btn;
-(void) viewDidLoad()
{
[btn setTitle:#"Hello" forState:UIControlstaeNormal]; //this is first way where there is no need to declare btn as property
[self.btn setTitle:#"Hello" forState:UIControlstaeNormal]; //this is second way where we do need to decalre btn as property as we are accessing it through self
//Setting value of name
name = #"abc"; //this is first way where there is no need to declare name as property
[self setName:#"abc"; //this is second way where we do need to declare name as property as we are accessing its aetter method through self
}
Now in the above code I wanna know when we can use the getter/setter methods of btn variable without declaring it as property then what is the need to declare it as property and which is the better way to set the value of "name".
Somewhere I read that when you want your instance variables to be accessed my other class objects then you should declare them as instance variables. Is it the only situation where we should declare them as properties.
Basically I am a little confused about in which situations to declare the instance variables as properties.
Please suggest.
Thanks in advance.
In short, you don't have to declare instance variables as properties unless you want to.
You declare a variable as a property in order to auto-generate getter and setter methods. In your property declaration you can specify how you want them set up (retain vs assign, atomic vs nonatomic). Then, the getter and setter are generated with the #synthesize directive.
So, again, there is no right or wrong way to use properties. Some people never use them, some people make every variable a property. It's really up to you.
typically, you'll use them because:
1) the property belongs in the public interface of the class
used when the class needs to expose a given method. the downside is that clients and subclasses may abuse the public interface (all objc methods are public, where visible), unless you're careful to hide these details (which is also a pain at times). sometimes you're forced to go well out of your way in order to achieve the class interface you need (with the proper levels of visibility).
2) you want auto-generated accessors
implementing nonspecialized accessors is tedious, and error prone. it's better to save the time and let the compiler generate them for you.
3) to document behavior
sometimes it's better to write #property (copy) NSString * title; instead of over-documenting the expected result.
4) stricter selector matching with dot-syntax
the compiler performs stricter selector matching. prefer to catch the errors/issues at compilation, if possible.
5) to force the subclasses to use them instead of handling the ivars directly
objc ivars are protected by default. you'll often want them to be private (depending on how the class is used and distributed, or just to ensure the subclass uses the base class correctly).
there are a ton of reasons for this. threading and maintenance are the big ones.
if you declare the ivar as private and provide a property for the subclass to use, then the subclass is forced to use the property in their implementation (although there are ways they could cheat) rather than giving them direct access to the ivar.
so... it ultimately depends on your preference, and the implementation details of your class, paired with the interfaces you're using. i don't think there's a hard and fast rule here - lesser evils and convenience are key motivations.

Private methods are appearing as public methods

I am trying to improve the design of my App by using private methods. Coming from .NET I am a little confused because I am declaring these methods in the .m file but from other files they are still showing up i.e. they are still accessible.
.m file:
#interface NSContentWebServiceController (private)
- (NSString *)flattenHTML:(NSString *)html;
- (NSString *)cleanseStringOfJsonP:(NSString *)jsonP;
- (void)retrieve:(NSasdf *)hasdel :(NSDictionary *)rootList;
- (NSString *)removeHTMLTagsFromString:(NSString *)aString;
#end
As JoostK said, there are no private methods in Objective-C like you have them in C++, Java or C#.
On top of that, the expression #interface NSContentWebServiceController (private) defines a so-called category in Objective-C. The term private here is merely a name for the category and has no meaning. Having something like yellowBunny in here would yield the same effect. A category is merely a way to break down a class into several pieces, but at runtime all categories are in effect. Note that a category is only able to add new methods to an object class, but not new variables.
For private categories it's now preferred to use the anonymous category, as in #interface MyClass(), as you then don't need a separate #implementation MyClass(yellowBunny) block but can just add the methods to main #implementation block.
See the "Categories" section in the Wikipedia entry on Objective-C for more information.
Private methods are only private in a way that they're not documented in a header file. Because of this you can't #import them into your project and thus will the compiler warn you about a 'selector not recognized' or something like that.
You'll be able to call these methods just as public methods, since it's just where you declare the prototype that makes a method private, Objective-C doesn't have such a thing as hidden, really private, methods.
At runtime, you will always be able to find all methods using introspection, so there really is no way of completely hiding your methods/properties.
You could add a id _internal instance variable which points to an object that does all the work, that way it's a bit more tough to call the private methods, although not impossible.