Where do I program a variable in an objective c class so all its methods can use it? - objective-c

I need to have 5 of my methods use a common variable, but I don't know where to declare it in my .m file. I know this is basic, but I'm quite new and I forgot where to put it. Please help me.

#implementation {
// instance variables here <---
int foo
float bar;
}
// methods here
#end

Related

How to write methods that should only be used within the class itself and are able to access ivars [duplicate]

This question already has answers here:
Best way to define private methods for a class in Objective-C
(12 answers)
Closed 9 years ago.
I have a class which has some methods that are only to be used within the class itself. These methods exist because I have a three-step process for the graphics work I'm doing, but I only want instances of the class to access the final result of those calculations, in a simplified example:
#import <Foundation/Foundation.h>
#interface GraphicsWorld : NSObject
#property(nonatomic, strong) NSMutableArray *objects;
#property(nonatomic, strong) NSMutableArray *adjustedObjects
/* three methods I'll never use outside of this class
I want to find a way to get replace these methods.
*/
-(void) calcTranslation;
-(void) calcRotation;
-(void) calcPerspective;
/* the one method I'll use outside of this class */
-(NSMutableArray *) getAdjustedObjects;
#end
I could define c-functions just outside of my implementation for this, but then they wouldn't have access to the properties:
#import <Foundation/Foundation.h>
#import "GraphicsWorld.h"
void calcTranslation()
{
// I'm useless because I can't access _objects.
}
void calcRotation()
{
// Hey, me too.
}
void calcPerspective()
{
// Wow, we have a lot in common.
}
#implementation GraphicsWorld
-(NSMutableArray *) getAdjustedObjects
{
calcTranslation();
calcRotation();
calcPerspective();
return adjustedObjects;
}
#end
Unless I'm misunderstanding your question, it sounds like you just want to hide your methods from being public? If so, just delete them from the header. You no longer need to declare methods in advance in objc (Xcode). The compiler will just find them internally now.
Make C-style functions (as you've shown) that take arguments and return values.
Make private Objective-C-style methods.
In addition to your #implementation section in the .h file, you can also have one in your .m file, which is private. Just as you declare methods and properties in the .h file's #implementation, you can do the same in the .m.
A method can be called whether it is declared private, or not put in the header file; due to the nature of Objective-C hiding methods is hard.
Hiding functions is a lot easier, just declare them static. To access the current instance you just pass in a reference to it - i.e. exactly what Objective-C does behind the scenes.
So for example:
void calcTranslation(GraphicsWorld *self)
{
// Access properties, instance variables, call instance methods etc.
// by referencing self. You *must* include self to reference an
// instance variable, e.g. self->ivar, as this is not a method the
// self-> part is not inferred.
}
and to call it:
-(NSMutableArray *) getAdjustedObjects
{
calcTranslation(self);
...

How Exactly To Use a Global Variable?

I'm a beginner with Objective-C, and am trying to use a global variable. I know that this question has been asked a hundred times, but none of the answers have worked for me. I'm trying to declare a BOOL variable in one class, and check its value in another. This is what I'm working with:
SController.h:
#interface SController : UIViewController {
BOOL leftSide;
BOOL rightSide;
}
SController.m:
- (void)viewDidLoad {
leftSide = YES;
rightSide = YES;
}
Now, for the class I'm trying to access the value of the BOOLs in:
#import "SController.h"
#interface VViewController : UIViewController
{
}
And VViewController's .m:
- (void)viewDidLoad {
// See what the BOOL values from SController are.
}
What I've tried:
Going off of the previous related questions on here, I've tried putting "extern" in front of the BOOLs declaration in SController.h, but that did not work. I tried simply importing the SControllers header file into VViewController, and that did not work either. I'm very new to Objective-C and programming in general, so I'm having a tough time wrapping my head around basic concepts like this. I understand the potential issues surrounding using a global variable, but this program is very small and for personal use. If anyone can show me what to change to make this happen, that would be great.
Like the others said, don't use a global variable for that (and most other) purpose.
You created iVars and in order to access them, you need to expose them to other objects.
You generally do that by defining #properties in your SControllers header file. When doing that, you don't need to create iVars yourself, they are created implicitly. And methods to access the iVars are also automagically created (getters and setters).
Your SControllers header could look something like this:
#interface SController: UIViewController
//no need to declare the iVars here, they are created by the #property definitions
#property (nonatomic, assign) BOOL leftSide;
#property (nonatomic, assign) BOOL rightSide;
#end
In your other viewController you need a reference to the instance of SController you previously created and want to "talk" to (it is important you understand this), then you could access the instance variable through the generated getter/setter methods like so:
//this is "dot notation", the first line would be equivalent
//to writing: [sControllerInstance setLeftSide: YES]
sControllerInstance.leftSide = YES;
BOOL valueRightSide = sControllerInstance.rightSide;
Please read up on: objective-c properties, getters/setters and dot notation.
You will find plenty of information on google and SO
I know this is not the answer you're looking for, but try rethinking your app. Global variables is not the best way to go for Object oriented programming.
Create GlobalVariable.h header class file and defined following externs as follows
extern NSString * googleURL;
And then in your implementation GlobalVariable.m file
#import "GlobalVariable.h"
NSString * googleURL = #"www.google.co.uk";
And then import the class wherever you want to use it across.
By default the variables (as defined in your code) are protected. You can add the #public keyword before the 2 variables to make them public but it's not recommended. Generally you want to expose those as properties using the #property keyword
Example:
#interface SController : UIViewController {
#public
BOOL leftSide;
BOOL rightSide;
#protected
//other protected variables here
}

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.

Why does Xcode 4 auto-generate a instance variable?

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

Call a variable from one file to the other

Of Objective C, I'm looking to call a variable from one .m to the other .m
This is given myvar declared as an int in Example1.h
Example1.m
myvar = myvar+10
Example2.m
if (myvar == 10){NSLOG("#myvar equals the correct integer: %i",myvar);}
However, by default myvar will equal 0 because myvar is called from Example1.h in Example2.m.
For global values, create a class to hold these and define the variables as static. You can also define class level methods to manipulate the static variable. I call my class appState. You might define myVar as static and then class methods (use the + not -) to get and set this variable.
Here's an example of a BOOL I can access from anywhere in my application.
account.h
#import <Foundation/Foundation.h>
#interface Account : NSObject
{
}
+(BOOL)isOffLine;
+(void)setOffLine:(BOOL)newValue;
#end
account.m
#import "Account.h"
#implementation Account
static BOOL _offline;
+(BOOL)isOffLine;
{
return _offline;
}
+(void)setOffLine:(BOOL)newValue
{
_offline = newValue;
}
#end
Now from any class in my application, I can #import account.h and then use something like:
if ([Account isOffLine]) {...}
or
[Account setOffLine:YES];
Note that I didn't create an instance of this class. I'm calling the class level methods. The value will persist between calls from different classes in my application.
I’d recommend you read up on the basics, perhaps Object-Oriented Programming with Objective-C could be a good place to start. My guess is that what you really should be doing is creating a property in one class and accessing it from another.