Why does Xcode 4 auto-generate a instance variable? - objective-c

I'm coming from C# development and just started to learn Objective-C and Xcode 4.
As far as I understand "#synthesize" is replacing getter/setter methods for properties if you don't need to check/control the values which are being read or written.
But why does Xcode 4 create a instance variable for me automatically?
Wouldn't this be enough:
#synthesize myProperty;
instead of:
#synthesize myProperty = _myProperty;
?
Why would I want to use/have the instance variable instead of the actual property if I don't have/need any getters or setters?
Thanks in advance!
MemphiZ
EDIT:
I understand that #synthesize is replacing getters/setters but what is this part good for: = _myProperty;?
Why would I want to have a instance variable if I could use "myProperty" directly? I would understand using "_myProperty" if the setter for example would check for a condition of the value. If I then want to skip this check I would use _myProperty. But as I use #synthesize I don't have a setter in place that does some check. So why do I have/want an instance variable then?
ANSWER:
See the comments in MattyG's post!

This is a convention used to remind the programmer to access the instance variables through the setters and getters with self. So if you're using:
#synthesize myProperty = _myProperty;
Then to access the variable directly you must write:
_myProperty = something;
To access the variable through it's setter you must write:
self.myProperty = something;
The benefit is that if you forget to access through self. then the compiler will warn you:
myProperty = something; //this won't compile
See this also this Question.

Well, you DECLARE a property's instance variable in the .h file, as well as the property itself. The interface to the property as well as the instance variable it'll use have been established with that... its implementation has not. That's where the #synthesize keyword comes in. It just implements the property for you, so that you don't have to write it out yourself.
Here are ways to declare properties in C#
private int _int1;
public int int1 {
get { return _int1; }
set { _int1 = value; }
}
This is a pretty common piece of code, and C# lets you abbreviate it to avoid having to type the same thing over and over
public int int1 { get; set; }
The difference between these two code segments is that the private variable "_int1" does not exist in the latter, since C# creates a variable internally. The #synthesize keyword is nice because it saves you the hassle of writing down the same code over and over while still allowing you to access the instance variable it's based on.
Edit. It's also important to note that getters and setters do exist in objective C. They just have different names than in C#, where they're labeled get{} and set{}. In objective C, the getter is a method with the same name as its instance variable, and the setter is a method with the word 'set' followed by the instance variable name with the first letter capitalized.
So, lets say you have this in your .h file
int myVar;
...
#property(nonatomic, assign) int myVar;
You can implement getters and setters yourself in the .m file
-(int)myVar {
return myVar;
}
-(void)setMyVar:(int)newVar {
myVar = newVar;
}
or you can just use #synthesize to have the getter and setter written automatically

Related

Define semi public variable in objectiveC

I'd like to define a member in objective C class that can only be read outside the class (public getter). The writing (setter) however shell remain private.
I've read that It's possible to conceal object's setter using the readonly property while exposing the getter using #synthesize syntax but I'm not sure how it works exactly.
Base on this information here's what I did, and I wonder what's happening here under the hood, and if this is the proper way of doing so ?
#interface MyObject : NSObject
//This line suppose to conceal both getter and setter.
#property (readonly) MyCppBaseObject *myCppBaseObject;
- (void)setMyCppBaseObject:(NSString *)SomeInput;
#end
// This line suppose to tell the compiler that the getter is exposed
#synthesize myCppBaseObject = _myCppBaseObject;
#implementation MyObject
-(void)setMyCppBaseObject:(NSString *)SomeInput {
if (someCondition) {
self.myCppBaseObject = new myCppObjectDerive1(...);
} else {
self.myCppBaseObject = new myCppObjectDerive2(...);
}
}
#end
P.S. I've seen a different approach explained in the following link, but I wish to understand the above implementation.
First, you should use the private extension described in the link you provide. That's the correct way to do this.
But to your question, what you've written here is not quite correct.
#property (readonly) MyCppBaseObject *myCppBaseObject;
This line makes a promise to implement -myCppBaseObject. That's all it does. It's just a promise. If you fail to live up to your promise, the compiler will auto-generate (synthesize) one for you using a backing ivar.
- (void)setMyCppBaseObject:(NSString *)SomeInput;
This line is not correct for your purposes. It's making a public setter. But you said you don't want the setter to be public. You could put this in a private extension, however.
#synthesize myCppBaseObject = _myCppBaseObject;
This asks the compiler to create a backing ivar _myCppBaseObject for the property myCppBaseObject. This is the default behavior, however, and so isn't required. (There was a time when it was, but that was a very long time ago.)
-(void)setMyCppBaseObject:(NSString *)SomeInput {
if (someCondition) {
self.myCppBaseObject = new myCppObjectDerive1(...);
} else {
self.myCppBaseObject = new myCppObjectDerive2(...);
}
}
This code is completely incorrect. It is an infinite loop, since self.x =... is syntactic sugar for [self setX:...]. What you mean is:
_myCppBaseObject = ...
You're going to create a lot of headaches having the name of the custom setter be exactly the expected name of the default setter, but with a different type. Don't do this. In theory it could work most of the time, but don't. Especially when there's dot-syntax involved. Especially since one of your objects does not appear to be ARC-compatible (i.e. a C++ object), this is going to really be a trap for really confusing problems. Name your setter differently.

getter and setter method in objective c?

New to Objective-C, and i am basically from c++ background. I am learning now objective-c and would like to get confirmation of what i understood is write or wrong?. Kindly advise.
I have the following class:
#interface Test: NSObject
{
int instance1;
}
#property int instance1;
- (void) sayHello;
#end
Class 'Test' has a instance variable instance1. If the member function ie: sayHello wants to access the variable, it has to happen through getter/setter functions. So, There are two ways to get it :
User can define.
We can get the help from the compiler?. How?.
declare the same variable as a property, and synthesize it, the the compiler
gets the code of getter/setter for us for that particular variable.
So, Untimately, getter/setter is the only way to access the variable in the method implementation, ie. both self.instance1 = 100; and instance1 = 100 need getter/setter.
Having missed both 1. and 2., there is no way to access the instance1 variable.
Also, instance1 is a pubic variable can can be accessed outside of the class with object instance.
Test *t = [[ Test alloc] init];
t.instance1 = 200;
Questions:
Is there any way to make instance1 is "private", so that I can not access the instance
variable outside the class?
Is there anything wrong in my understanding?
If the member function ie: sayHello wants to access the variable, it has to happen through getter/setter functions.
It doesn't have to. You can access ivars directly, without using accessor methods:
- (void)sayHello {
instance1 = 123;
}
You can define private ivars by declaring them in the implementation file, not the header:
#implementation Test {
int privateVar;
}
// ... additional implementation, methods etc.
#end
Note, that since Xcode 4.4 you don't have to declare your ivars anymore. You simply declare a property. The ivar and the accessor methods will be synthessized automatically.
For more details, I recommend reading my answer to this question: Declaration of variables
ion SomeDelegate.h
#interface SomeDelegate : NSWindowController {
#private
int fLanguage;
int fDBID;
bool fEndEditingIsReturn;
#public
int fIsMyLastMSG;
}
#property int language;
In SomeDelegate.mm
#implementation SomeDelegate
#synthesize language=fLanguage;
In my example you get private and public variables, private variable fLanguage has a property for synthesize accessor methods.

Objective-C property and synthesize logic

What is an actual name of instance variable, say, topSpeed, as from lectures of Stanford University about the Objective-C and iOS development?
Here is the code:
#property (nonatomic) double topSpeed;
Looking at this code I will think that I have defined a variable topSpeed in the class.
I can't understand why it will declare automatically the getter method with the name the same as the variable name - topSpeed?
Another question is when we use
#synthesize topSpeed = _topSpeed
And if we look at what the #synthesize will generate:
- (double) setTopSpeed:(double)speed
{
_topSpeed = speed;
}
- (double) topSpeed
{
return _topSpeed;
}
What is _topSpeed here and what is topSpeed? I have declared a variable topSpeed, not the _topSpeed. What if I don't use property what would the variable name be?
In the earlier days of Obj-C and still today you declared variables in your class's header file like so:
#interface MySubclass : NSObject {
int varName;
}
Then you would have to manually create setter and getter methods to access the variable outside your class. In order to help deal with memory management (useful for objects), Apple introduced properties in Obj-C 2.0 and it allowed you to define the accessors for a given variable. You could say that a variable would have certain attributes (such as retaining or copying a value, having alternate setter or getter name, etc) and you defined this like:
#property (someAttributes) int varName;
then in your #implementation you could #synthesize these properties with the given attributes and the compiler would generate setter and getter methods for your variable.
#synthesize varName; // Generates -setVarName: and -varName for you
Now, today the idea is that you can move away from implementing the instance variables in the {} section and just declare a property and a synthesize. What we get if we just say
#property (nonatomic) double topSpeed;
#synthesize topSpeed;
is a setter and a getter called setTopSpeed: and topSpeed with an instance variable called topSpeed (created by the compiler) to store the value. The idea behind #synthesize topSpeed = _topSpeed; is that the instance variable name will be _topSpeed but the accessor names will still be -setTopSpeed: and -topSpeed. This helps for code readability because there can be confusion between when you say self.topSpeed or topSpeed in your code (the first calls the accessor the second is the ivar). The _topSpeed differentiates itself from normal variables and also makes it explicit when you're calling self.topSpeed (the accessor) vs _topSpeed (the ivar). Apple is moving to this underscore syntax as well so don't think that it's going extinct, because it's quite the opposite. Update: (See Tommy's comment)
It also helps with variable naming collisions. If you had to implement setTopSpeed: yourself it would look something like this:
- (void)setTopSpeed:(double)topSpeed {
_topSpeed = topSpeed; // _topSpeed makes it obvious it's an ivar
}
It's a syntax sugar, let you type less word.
Unlike java/c++, in obj-c you can't access variable of class. You could only call It's methods.
#synthesize topSpeed = _topSpeed means You want an variable named _topSpeed and has Accessors named topSpeed and setTopSpeed.
#property (nonatomic) double topSpeed; is not a pure variable declaration, It will also declare Accessors too. A pure variable of a class Foo will look like this :
#interface Foo:NSObject{
double topSpeed;
}
For the first question the answer is "naming convention". So it is only a naming convention. If you want to access the topSpeed variable, the "get" part is not significant - like [car topSpeed] is easier to read than [car getTopSpeed]. As for the second question, I am not sure but I believe you access the topSpeed property through the variable _topSpeed.

Creating Properties in Obj-C, how do I write the default Getter?

I'm just starting to learn Objective-C, one thing I'm trying to learn is good Property use. I'm currently trying to create some properties with custom setters. This is how far I've gotten:
#interface MyClass : NSObject
#property (nonatomic, assign) int myNumber;
#end
#implementation MyClass
#dynamic myNumber;
- (int)myNumber {
return ???;
}
- (void)setMyNumber:newNumber {
myNumber = newNumber;
// custom stuff here
}
I really just want to implement a custom setter, I'm fine with the getter being default. However, how do I access the variable directly? If I put "return self.myNumber", won't that just call the getter method and infinite loop?
Property access functions are only called when using the x.p notation. You can access the instance variable backing the property with just p (in Objective C, all members have the class instance variables in scope). You can, if you really want, also access via the pointer deference notation ->. So, any of these two:
return p;
return self->p;
However, you needn't use #dynamic here. #synthesize is smart, and will only create defaults if you've not provided them. So feel free to just
#synthesize p;
Which will create the getter, but not the setter in this case.
- (int)myNumber {
return myNumber;
}

Why put underscore "_" before variable names in Objective C [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How does an underscore in front of a variable in a cocoa objective-c class work?
In objective C I am seeing lots of code with a underscore before variable names e.g _someVariable
why is that? also how to you write accessors i.e get and set method for such a variable.
The underscores are often used to show that the variables are instance variables. It is not really necessary, as ivars can have the same name as their properties and their accessors.
Example:
#interface MyClass : NSObject {
NSString *_myIVar; // can be omitted, see rest of text
}
// accessors, first one is getter, second one is setter
- (NSString *) myIVar; // can be omitted, see rest of text
- (void) setMyIVar: (NSString *) value; // can be omitted, see rest of text
// other methods
#property (nonatomic, copy) NSString *myIVar;
#end
Now, instead of declaring and coding the accessors myIVar and setMyIVar: yourself, you can let the compiler do that. In newer versions, you don't even have to declare myIVar in the interface. You just declare the property and let the compiler synthesize the rest for you. In the .m file, you do:
#implementation MyClass
#synthesize myIVar; // generates methods myIVar and setMyIVar: for you,
// with proper code.
// also generates the instance variable myIVar
// etc...
#end
Be sure to finalize the string:
- (void) dealloc {
[myIVar release];
[super dealloc];
}
FWIW, if you want to do more than the default implementation of the getter or setter do, you can still code one or both of them yourself, but then you'll have to take care of memory management too. In that case, the compiler will not generate that particular accessor anymore (but if only one is done manually, the other will still be generated).
You access the properties as
myString = self.myIVar;
or, from another class:
theString = otherClass.myIVar;
and
otherClass.myIVar = #"Hello, world!";
In MyClass, if you omit self., you get the bare ivar. This should generally only be used in the initializers and in dealloc.
Don't do it.
Single leading underscores are an Apple internal coding convention. They do it so that their ivar names won't collide with yours. If you want to use a prefix on your ivar names, use anything but a single underscore.
this is a naming convention normally used for c++ to define instance variable which are private
like in a class u may have
private:
int __x;
public:
int GetX()
{
return this.__x;
}
this is a naming convention, i was forced to use in c++. However my teacher never told us the name of the naming convention. But i feel this is helpfull and readable specially when u are not using java naming conventions.