How to use properties in Obj C [closed] - objective-c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I was trying to learn how to use properties in iOS programming.
I just want to check with people here if what I got is right?
Say I have a property
#interface Person : NSObject
#property NSString *firstName;
#end
in implementation
#implementation XYZPerson
#synthesize firstName;
...
#end
By this,
a) an instance variable named: firstName is created
b) whenever I want to use property inside my class, I call self.firstName (or setter/getter)
c) I can initialize the property in the init method like this:
-(id) init {
...
self.firstName=#"SomeText";
...
}
I believe the points I mentioned above, are correct, right?

What you say is pretty much correct although you are missing a few things from your #property declaration. You need at the very least a property attribute like strong or copy or assign. For strings which might be mutable, we generally use copy to ensure the string can't be modified from under us. So #property (copy) NSString *firstName. See this answer for more details about this.
Most people use nonatomic as well to improve performance by disabling thread synchronization in the generated getters/setters. See this answer for more information.
Some people recommend against using property accessors in the init method (preferring direct ivar access) because subclasses might have overridden the setter/getter and might not work correctly until the object is fully initialized. Practically speaking you very rarely need to worry about this so a lot of people ignore this advice.
With the latest version of Xcode you also don't have to add the #synthesize manually - an underscore-prefixed instance variable (_firstName in your example) will be synthesized for you automatically.

Related

Why don't #interface, #imp... and #end require a semicolon at the end of the line? Also, are there other instances where this is the case? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I know the "#" symbol is used to show Objective-C keywords, but I don't understand why some of these keywords require a semicolon, while some don't.
Namely, as far as I can see; #interface, #implementation, and #end don't require a semicolon
#interface EditorPrintView ()
#property ImageDocument* editorDoc;
#property NSColor* backgroundColor;
#property BOOL paginate;
#property CGFloat scale;
#end
#class ImageController;
#implementation EditorPrintView
...
#end
Does anybody know of any specific reason why this is? If this is just an artifact of history, then I'll buy it, but I wasn't able to create a good search query to find any answers.
We can only speculate on the motivation of Objective-C's designer, Brad Cox. (I suppose we could also try to contact him…)
I believe Brad Cox originally implemented Objective-C as a preprocessor that transformed Objective-C into plain C in a fairly straightforward way. It might have been easier to write the preprocessor by not requiring semicolons.
For example, keep in mind that #interface can be followed by a brace-enclosed block of declarations, e.g.
#interface MyObject : NSObject {
int _count;
IBOutlet NSView *_view;
}
...
#end
Perhaps it was easier to write the preprocessor to handle this optional block by not allowing a semicolon after the #interface declaration.
Also, since the #-declarations are not part of the plain C language, perhaps Brad Cox chose to treat them more like the C preprocessor's #-directives, which were (at the time Objective-C was invented) handled by a preprocessor and don't require (or generally even allow) semicolons. So #interface … #end is like #if … #endif.
These days, it would probably be trivial to write the compiler either way (allowing or disallowing semicolons), but there's no reason to change that part of the language now.
As for other directives that don't require a semicolon: there are #protocol declarations, and there's #optional, #required, #public, #private, #package, and #protected.

difference between view controller and normal model class when declaring property? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
i was just figuring out how to have private variable with class extension.
And what i noticed was that there is no default code for class extension inside a normal class.
And when i try to declare variable with #property, it does not allow me but to type #protected and #private while inside ViewController, it only allow me to have #property #optional #required.
SO, my question is that is there any reason for that..? What is the difference and what makes it different..?
You didn't post any code, leaving us to infer what you're doing. I'm going to assume it's something like this:
#interface ViewController ()
#property id someProperty; // This works
#private
id someVar; // This does not work
#end
and:
#implementation ModelClass
{
#property id someProperty; // This does not work
#private
id someVar; // This works
}
#end
Assuming that's true, it seems you're confused about the nature of properties vs. instance variables. #property is essentially a way to declare accessor methods, for which the compiler (by default) automatically synthesizes method implementations and a corresponding backing instance variable. Instance variables on the other hand, are simply per-instance variables, not methods at all.
The first block of code above is a class extension on ViewController. Class extensions allow you to declare additional methods -- and thereby #properties too -- separately from the main/public interface for a class.
The braces after #implementation in the second block denote a place to declare additional instance variables (only).
#protected and #private are visibility modifiers for instance variable declarations, and control whether an instance variable is visible only to instances of the class itself (#private), instances of the class and its subclasses (#protected), or publicly (#public). These modifiers cannot be used for methods (of which #properties are a special case). Afterall, in Objective-C, methods are actually always public in the sense that it's only at runtime that a message send is turned into a method call, and the compiler can't truly enforce a limitation on calls to "private" methods.
Finally, to answer what I think is the heart of your question, you most certainly can add a class extension to your model class in order to declare additional "private" #properties and other methods. Xcode may not include one in the default new file template for non-view controllers, but that doesn't mean you can't add one yourself:
#interface ModelClass ()
#property id somePrivateProperty; // Works just fine
#end

Why use self if code works without it? [duplicate]

This question already has answers here:
Difference between class property mVar and instance variable self.mVar
(3 answers)
Closed 9 years ago.
Really, why most of people use self.something for almost everything when code works without it?
for example:
-(void)viewDidLoad {
self.mylabel.text = [NSString stringWithFormat:#" %#", someVariable];
}
The code works the same way without self.
I have tried to see what happens without self and it always works.
Using self. means that you are using the getter/setter, and not using it means that you are accessing the instance variable directly.
This question has been treated a lot here, but summarising:
ALWAYS create a #property for every data member and use “self.name” to
access it throughout your class implementation. NEVER access your own
instance variables directly.
Properties enforce access restrictions (such as readonly)
Properties enforce memory management policy (strong, weak)
Properties provide the opportunity to transparently implement custom
setters and getters.
Properties with custom setters or getters can be used to enforce a
thread-safety strategy. Having a single way to access instance
variables increases code readability.
Source:
Best Practices fr Obj-C

Property and synthesize in iOS [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
#property #synthesize
When must I use property and synthesize for an element as NSArray, NSSTring....or IBOutelt as UIButton or UITextFiled?
A property is used mainly when other objects need to change or access the ivars in your object. Without manually defining getters and setters, or using #property, other objects can't see or change the ivars. Properties are also often used for convenience of memory management, assisting you in preventing memory leaks.

Implicit data members for #synthesize - good practice or bad habit? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Today, I got a link to a long list of coding guidelines, proclaiming to be "code commandments". A good read, and full of new insights to me. Among the list, somewhere along 25% of the scrollbar, I come across something new to me: Implicit data member creation.
Although every tutorial, book and video I've read or watched about Objective-C always performs the triad of NSNumber *number | #property NSNumber *number | #synthesize number, these commandments now tell me I can simply omit the first step (data member declaration in the interface) because #synthesize will create one on the fly. Say what!?
With a little disbelief I deleted several of my data member declarations, and indeed, my app still works like a charm. Less typing, less reading, less chance for typos.
Sounds to me like a win-win-win, but is it really good practice?
I'm asking this question out of pure disbelief that all the tutorials, books and videos are teaching the wrong lesson, at least too much of it, or that I've been not paying attention in class...
Cheers,
EP.
Edit: Although I copied the expression "data member" from the linked post, it is more commonly described with the word "ivar", just a good one to have in here for search friendliness. This also takes care of my former confusion over property/ivar/member naming :).
Synthesized instance variables are a feature of the modern Objective-C 2.0 runtime. This means they're available on x86_64, on ARM, and as of Xcode 3.2, on the iPhone Simulator. It means exactly what you suggested - you can omit the ivar declaration, and the #synthesize line will generate the ivar for you. The performance of this is exactly the same as declaring the ivar explicitly, but it has the very important benefit of not polluting your header file with private implementation details.
I have begun the practice of removing synthesized properties from the Objective-C classes I create. The primary reason for this is because there is a distinct difference between:
self.myNSObject = [NSObject new];
and
myNSObject = [NSObject new];
Specifically, if myNSObject is declared as a #property(retain, ...) the former line will result in a retainCount of 2 while the latter will result in a retainCount of 1. This means that unless you are extremely careful about every assignment to myNSObject you run the risk of getting your retain/release balancing wrong.
The other reasons you specify are also very valid. There is a lot going on in the synthesized routines that my brain doesn't account for when I'm reading the code I've written, so a lot is taking place behind the scenes that I'm not thinking of yet am accountable for. It's for very a similar reason I've abandoned Apple's Interface Builder.