Usage of Properties in iPhone Programming [duplicate] - iphone

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there any reason to declare ivars if you're using properties exclusively in Objective-C?
ObjectiveC ivars or #property
I am new to iPhone programming (and the programming scene altogether). I have tried to study about Properties at various places and found out that they are basically the shortcut to making getter and setter methods for other classes to get access to those objects.
Now, I have seen programmers define the object in the curly braces after the #interface:UIViewController as well as in the properties after that when all the accessing will happen within that class' .m file.
Now, that superfluous (?) piece of code, is it necessary? Is this a standard? Looking forward to some intelligible opinions.
Thank you in advance.

I can interpret your question in a number of ways:
Question: Why do some programmers use properties and instance variables (the variables defined within the curly braces), and others just use properties, and other just use instance variables?
Answer: As you know, #property declarations will, when you #synthesize them, will generate the getters and setters for you. Historically, this is all that it did for you and you had to also manually declare your instance variables. Later, the compiler was improved so that if you didn't have the instance variable defined, that the #synthesize statement would generate that, too. When this was first introduced, common practice was to define both the property and the instance variables, but Apple eventually shifted their guidelines and encouraged programmers to not define instance variables, but let the compiler generate that itself from the #property and #synthesize declarations.
So, in answer to your questions: 1. defining instance variables for your properties is now superfluous; 2. it is no longer necessary; and 3. it is now standard to not explicitly declare instance variables, but rather to let the #synthesize statement do that.
As an aside, the convention on the #synthesize statement is to, with an property called var, to precede the instance variable name with an underscore, thus #synthesize var = _var. This is done to minimize the chance that a programmer might accidentally refer to an ivar when the property was intended (or vice versa). To further illustrate that this is the preferred standard, starting in Xcode 4.4, even the #synthesize statement is optional (thus, define the #property, but no ivar, and no #synthesize) and it will declare and ivar the same name as your property, except with a leading underscore.
Question: Why do some programmers define some of their properties and instance variables in the .m file? Why do other programmers declare some of their instance variables and properties in the .h file when they're only being used within the class's own .m file.
Answer: Those instance variables and properties defined within the .m file (in what is called a class extension) are just a convenient way of defining those ivars/properties that are not advertised to the world. In this convention, your .h file becomes just your public interface (what properties and methods can be invoked from elsewhere) and everything else goes in the .m file. It's a nice way to keep your interfaces a little cleaner so when you go to use your class at some future date, you can just look at the .h file and not get too lost in the details of the class's implementation details.
In the past, before class extensions became prevalent, we defined all of our instance variables and properties in the .h file, even if they were private and used only within the class's own .m file. Thus, you'll still see some code that does this.
So, in answer to your questions, 1. it's not superfluous to use class extensions (unless your class extension is empty, but even then I tend to keep it so I can see that there are no private ivars/properties); 2. the use of class extensions is not necessary; but 3. the use of class extensions for private properties/variables that are used only within the class itself is an emerging standard and probably does represent best practice.

Related

When to use #property? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why should I use #properties?
When to use properties in objective C?
I have been programming in objective-c for a little over a year now, and I always felt like it was a convention to use #property and #synthesize. But what purpose do they really serve ? Are they solely there to be communicated between classes ? So, for instance, if I use an NSMutableDictionary only in the scope of the class where it was declared, an omission is O.K. ?
Another question:
If I set the property of an NSMutableDictionary, it is retained, right ? So, in my class I don't have to call alloc() and init(), do I ?
What are the rules to use properties ?
But what purpose do they really serve?
Access control to iVars and abstraction between representation and underlying data.
Are they solely there to be communicated between classes?
No, they are for when you want to control access to iVars instead of accessing them directly or when you could in the future change underlying data structures but wish to keep the current representation.
So, for instance, if I use an NSMutableDictionary only in the scope of the class where it was declared, an omission is O.K.?
It depends. Do you want to have controlled access to the iVar? Would it be possible for your code to change so the dictionary is fetched and not a direct iVar. Usually, the answer is yes.
If I set the property of an NSMutableDictionary, it is retained, right?
Depends on how you declare the property.
So, in my class I don't have to call alloc() and init(), do I?
You have sloppy wording here. I think you are asking if you still need to construct an instance of a property. Yes, you will need to construct an instance of a property in some way. There are lots of ways of doing this.
NOTE: the convention for talking about methods is use their signature. Instead of alloc(), you would use -alloc.
What are the rules to use properties?
This you will need to read the doc for.
Like in another languages, when we want to make our variable global or public we use public access modifier. In objective c when we want access our another class variable in other class, we use #property and #synthesize them. Basically #synthesize is way by which compiler create a setter and getter methods for that variable. You can manually create them but not use #synthesize.
By creating object of that class you can access your property variable in other class.
By using retain, you clear that is take place memory and not exist until that container class not goes dispose or released.
Properties simply make your life easier.
Nowadays use properties as much as you can in terms of memory management, code-style and timesaving.
What do #propertys do?
They can create getter and setter methods (depends on given parameters).
Normally you declare instance variables in the header file (like in c++).
Now you simply let that be and instead of that declare the properties you want for instance variables.
Properties can get multiple arguments.
For normal objective-c objects, where you need a pointer (*) you would write.
#property (nonatomic,retain,...)
When you #synthesize it it creates a getter and a setter.
The setter automatically does stuff like releasing your old object, that your variable hold and retaining the new one.
So you don't have to do that manually (which should be quite often the case). Thats important.
You also can give it arguments (readonly,readwrite) to decide if to set a setter or not.
You can even declare a #property in the header file readonly and override that in your implementation file with a extension (a category with no name).
To dive deeper into this, read the apple developer manuals, which are quite effective.
Hope that helps a bit.
Shure it is the tip of the iceberg, but it's mostly everything you need.

Regarding self. in viewDidUnload [duplicate]

This question already has answers here:
When should I use the “self” keyword?
(6 answers)
Closed 9 years ago.
I have an attendant question to iPhone: Why do I need self.<> in viewDidUnload?
Since there is a difference between using self.instance and instance, when is only instance actually used? Just setting the reference to nil seems quite useless? Why is the option there?
Generally, you'll find a lot of useful information here: http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html%23//apple_ref/doc/uid/TP40004447-SW4
For the rest of this answer, I'll assume that you are referring to properties automatically synthesised with the #synthesize directive in your .m files.
Executive summary
When you use the form self.property, retain/release is automatically taken care of for you. When you use the form instanceVariable without the self prefix, you're on your own with retain/release.
Longer explanation
When you omit the "self." part, what you really are doing is that you access the automatically generated underlying ivar which the compiler has given the same name as you have given to the property.
If you don't want the compiler to generate ivars of the same name, then you can use an extended form of the #synthesize directive, like this:
#synthesize myvariable=__myvariable;
That way, you will ask the compiler to create an underlying ivar called __myvariable instead of the default myvariable.
Using this extended form, you would refer to either self.myvariable (as a property) or __myvariable (as an instance variable), which can be handy to visually distinguish the two types of access.
With that in place, we can get to the substance of the matter.
When you use self.myvariable, you implicitly call the accessor methods (possibly synthesised for convenience), like this:
self.myvariable = #"Some string";
is equal to
[self setMyvariable: #"Some string"];
or, in the case of a right hand use of the property
myLocalVar = self.myvariable;
is equal to:
myLocalVar = [self myvariable];
The examples above use the accessor names recommended by Apple.
On the other hand, when you use the instance variable directly, you just assign the variables directly without going through the accessors.
Now, one huge advantage of using the accessors on the iPhone is that the automatically synthesised accessors also take care of the retain/release messages, so you don't have to worry about that - or waste code lines handling this somewhat tedious stuff.
Since there is no need to worry about retain/release when you are just reading a property, you could argue that you only need to use the property syntax (with self.) on the left side of an assignment, so whether you want to use the self.-syntax on the right hand side of an assignment is partly a matter of style.
Personally, I have developed a style where I try not to refer to automatically synthesised ivars, unless I have specified them in the #synthesize directive. Otherwise Apple might one day change the way an unspecified #synthesize directive works, and my builds would break. But that is just a personal precaution of mine.
There is one exception to all this, as stated in the docs linked at the top of this answer - and that is that you should not use accessors to the class' own instance variables in the init* methods. One the Mac, you shouldn't use them in the dealloc methods, either, but this is one point where Apple's coding recommendations differ between the two platforms.
Ok, this was a long answer to just say, read the docs, but I hope it clarifies things a little. Memory management in reference counted environments is not trivial, so don't despair if it isn't clear at first.
PS: And if you think this the sort of worries that others should solve for you, log a bug with Apple to ask for garbage collection on iOS. It works nicely on 64-bit OS X.

How to declare instance variables and methods not visible or usable outside of the class instance?

I've looked through a bunch of posts on this subject. Maybe I didn't run across "the one" and someone will point me in that direction. The question is simple and probably has a simple answer.
If you have two ivars, say, "public_ivar" and "private_ivar", where/how should you declare them so that what is public is public and what is private is not exposed in any way to anyone looking at the header file?
Same question in the case of "public_method" and "private_method".
I like clean header files (in other languages) that only expose the methods and ivars I want someone else to see. You should be able to publish your header file and not run into the danger of someone accessing something they are not supposed to. How do you do that in objective-C.
For example, let's say that I decide that I need to use an ivar to keep track of some data, a counter or somthing like that, between various class methods that all need access to this information. If that ivar is declared conventionally in the header under #interface its existence is publicly advertised and it is usable by anyone creating an instance of the class. The ideal scenario would be that this ivar would not be visible at all outside of the class implementation.
You can declare instance variables or declared properties in a class extension. Since a class extension is declared in an implementation file (i.e., not a header file), they won’t be visible to someone inspecting the header file. For instance, in the header file:
#interface SomeClass : NSObject
#end
and in the implementation file:
#interface SomeClass ()
#property (nonatomic, assign) int privateInt;
#end
#implementation SomeClass
#synthesize privateInt;
…
#end
or
#interface SomeClass () {
int privateInt;
}
#end
#implementation SomeClass
…
#end
Note that there’s nothing preventing access to private/class extension instance variables (or the accessor methods for properties declared in a class extension) during runtime. I’ve written a rather detailed post about this as an answer to another question on Stack Overflow: Does a private #property create an #private instance variable?
Edit: Instance variables in class extensions were presented in WWDC 2010 session 144.
Edit: "Using the Clang/LLVM 2.0 compiler, you can also declare properties and instance variables in a class extension."
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocCategories.html#//apple_ref/doc/uid/TP30001163-CH20-SW1
Use class extensions to add to a class in your implementation file. A class extension is basically an unnamed category with a few bonuses: properties declared in it can be synthesized and anything declared in it must be in the main implementation, so the compiler can check to make sure you didn't miss an implementation. You must put the class extension before your implementation. You can't add instance variables directly in a class extension, but you can add properties. When you synthesize accessors for properties which don't have corresponding instance variables, the new runtime (os x 10.5 and later and all versions of iOS, I believe) will create the instance variables automatically. This means you can't create your own accessors, however, unless you put the instance variable in your header. Private methods can be added to the class extension without restriction, but as Anomie noted, it is technically possible to use them if you know what they are called, and with class-dump, nothing is safe.
Example usage of a class extension:
#interface MyClass ()
#property (retain) id privateIvar;
#property (readwrite) id readonlyProperty; // bonus! class extensions can be used to make a property that is publicly readonly and privately readwrite
- (void)privateMethod;
#end
#implementation MyClass
#synthesize privateIvar; // the runtime will create the actual ivar, and we just access it through the property
- (void)privateMethod {
...
}
...
Another way of creating "instance variables" without putting them in the header or using a property is to use associative references, which add data to an object at runtime. They aren't technically the same as instance variables, and the syntax for them is more complex. Since they also require the new runtime, there are only two reasons you would ever really want to use them: you want to add an instance variable in a category (outside the scope of this question) or you need it to be really really private. An associative reference doesn't create any methods or add to the class's definition in the compiled code, so if you don't create wrappers for them it is impossible to find out about them without asking the object after you add the data. See the bottom of the page I linked for a complete usage example.
You can use #private to specify that ivars are private. There is no way to make a method private, however. Even if the method is not listed in the header file, if someone knows the name and arguments they can call it.

Why should I use #properties? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What describes #property(…) best? What's that actually good for?
If I declare a variable in my class interface, I can use such variable anywhere on my class. Awesome.
If I use #property (retain) Something *myVar; I can access that variable with self.myVar... But, what is the difference? Is there a good reason I should use one method or another?
Short answer: Encapsulation of memory management.
Longer answer: You need to establish ownership of an object if you want to use it later. If you want to use it later, you'll need a reference to it with which to do so, and a great place to keep that reference is in an instance variable.
You could handle the ownership claims (i.e. retains and releases) each time you assign a new value to that, but that would leave a lot of repetitious and trouble-prone boilerplate code scattered all over the place, like cherries in a fruitcake. That kind of mess is fiendishly difficult to debug when (not if) something goes wrong. So, it's far better to wrap that code up in accessor methods, so you can write it once and then forget about it.
But accessor methods are mostly boilerplate too, so we use #property declarations to create them automagically, rather than writing them by hand.
Edit: Apple's Memory Management Guide provides a lot of detail about what the accessor methods generated by #property do behind the scenes.
If I use #property (retain) Something *myVar; I can access that variable with self.myVar... But, what is the difference?
#property (retain) Something *myVar;
// this property declaration declares:
- (Something *)myVar;
// and
- (void)setMyIvar:(Something *)arg;
// and is accessible by dot syntax.
// it also declares and/or documents how the ivar is managed (copy, retain, etc.)
in use:
// direct access to the ivar. zero additional overhead (with regard to accessing the ivar)
[myVar message];
// properties used with dot syntax invoke the accessor. therefore,
[self.myVar message];
// is the same as:
[[self myVar] message];
the property's properties also give instructions to the compiler as to how to synthesize an accessor.
Is there a good reason I should use one method or another?
in init and dealloc, access the ivar directly - you are interested in initialization and cleanup of the object's ivars and do not care about subclasses. using properties here can also introduce bugs or undefined behavior.
for other cases, that is, when the object is in a fully constructed state, you should always use the accessor for consistency. if a subclass overrides an accessor, direct access of the ivar could break designs.
if you want to avoid this, then make the ivar private and do not declare a property for it. if you do declare a property for it, then document that it is private; i'll typically write #property (retain) Something * private_myIvar; in this case. in this case, it is convenient to use a property to synthseize the ivar's memory management.
when the ivar is private, you have total access to it. it is safe to access directly or by private property. otherwise, assume that you must use the accessor.
if myIvar is declared private and will be created only at initialization, you can avoid declaring the properties altogether. this will reduce runtime overhead (if that is critical). messaging overhead, retain/release cycles, and atomics will (naturally) require more execution time. so it can be bypassed to improve performance.
visibility/maintenance. sometimes, it's far less maintenance/implementation to hide an ivar from the interface. in other cases, the ivar is an implementation detail of the class, and should not be a part of the public interface. in such cases, consider making it private (there are a few ways to accoomplish this in objc).
Using the #property to access your ivars, does a lot of the repetitive code of releasing and retaining objects for you. You don't have to use them. It's just a lot of tutorials make it simple for people that are new to the platform.

How can I avoid redundancy while declaring new class attributes in Objective-C?

In my code, every time I need a new object attribute for my class, I typically copy/paste its name in 4 different places!
The declaration in the header file (NSObject * myObject;)
The #property() line
The #synthesize() line in the implementation
Releasing it under dealloc: (only for objects of course)
I do this because it works, not because I completely understand what's going on. I do know that the declaration in the header file allows other classes to see its attributes, the property specifier determines how its getter/setter methods will be constructed. And the synthesize line actually builds those getter/setter methods. I also know that primitive types should use (nonatomic,assign) instead of (nonatomic,retain), but I have no clue when I should omit the nonatomic.
What can I do to avoid redundancy in my code. If I change or add a variable in my class I have to check 4 different places, and it gets old really fast. Are there any key strokes to make this process faster? Are there lines of code I can simplify or combine to obtain the same result?
Accessorizer will automate a lot of this for you.
In the latest version of Clang (Ships with XCode 4, not in XCode 3 yet) you get default #synthesize as well as default ivar creation. The default ivar creation already works, but not on the simulator. With both of these features all you need to do is add the #property line and deal with the memory management in dealloc
As far as nonatomic vs atomic. atomic is the default, and what happens when you leave off the nonatomic annotation. Atomic guarantees that the value is completely set before allowing anything to access it, nonatomic doesn't. Atomic is only useful in threading situations, and is slightly slower in singlethreaded applications.
It's important to understand what each of those lines of code does. They are not all the same and they are not necessarily redundant. One thing that will help is to use the correct terminology — for example, with NSObject *myObject; you're probably referring to an instance variable declaration.
First and foremost, a #property declaration in an #interface lets you say that instances of a class expose a piece of state. It doesn't say much about the implementation of that state, only that it's exposed by instances of your class and the API contract (memory management, atomicity, methods) for the state.
The #synthesize directive tells the compiler to create or use a specific instance variable as storage for a declared #property. This does not need to be how you provide storage for a property. For example, Core Data provides its own storage for modeled properties, so you use #dynamic for those instead. You also don't need to use an instance variable with the same name as your #property — to extend your example above, you might name your instance variable myObject_ while naming your property object and that's perfectly fine.
Finally, you send the instance variable -release in -dealloc — for an object-type property marked retain or copy — because you've said you'll manage its memory. You're not releasing the property, you're releasing the storage. If you implemented the storage some other way, you'd clean it up some other way.