Global variables? - iphone

How do I use global variables in x-code(iphone). For example, lets say i want to declare a bunch of variables(NSStrings) in the viewcontroller file, then how would i access them throughout my different classes? Can someone help me?

Global variables are global variables. You use them the same way you would in any C program, which is to say typically they'd be declared in something like "globals.h" and imported wherever needed.
With that said, it's generally poor practice to rely on globals. You might have an "ApplicationController" object which in essence tracks the global state of the application, but its variables should be instance variables and either accessed only internally, or via getters/setters.
If you wanted to declare a bunch of strings in a single object to be referenced by many other objects, typically you'd make that object a Singleton and pass a reference to it to each object needing access to it.
However, you need to ask yourself WHY you need to do that and if there isn't a better way. I'll bet dollars to doughnuts there's not a good reason for what you're trying to do.
Give us some more details on what the overriding need is for these strings to be global, and then we can show you reasons why they don't. :)

You may use a singleton if it's not too over-killed. Another option is NSDefaults. Of course, the simplest way is simply define an extern in .h
extern NSString * const STR_1;
and the value in .m:
NSString * const STR_1 = #"String One";

just declare your variables in the .h file and then import this file in any class you want to use it. You can make any type of object or variable global.

If you declare the variable in delegates, You can access those variable in any other controllers using setter and getter methods to access.
See Warrior Answer
I hope,it will help you.

Related

Usage of Properties in iPhone Programming [duplicate]

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.

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.

iPhone Global Variable?

I have two views with their own .h and .m files of course. How can I declare a bool (or any variable for that matter) in one view and be bale to access it in another view?
Thanks.
Objective C is a superset of plain ANSI C, so you would create and use global variables exactly the same way as in old-fashioned C.
In exactly one .m or .c file, put:
BOOL gMyGlobalBoolVar = NO; // or YES, depending on whatever initial state is needed
I might place these in a centralized singleton class, such as your appdelegate .m file, or in a separate .c file, such as myGlobals.c. I usually place these after the #imports/includes but before any class, method, or function definitions to clarify that they can be accessed outside of any object or function.
In the .h files for all classes where you want to access gMyGlobalBoolVar, put:
extern BOOL gMyGlobalBoolVar;
Then just use them anywhere in the class:
if ( [ self dogHasFleas ] ) {
gMyGlobalBoolVar = YES;
}
The use of global variables is currently not "politically correct", but for quick code that you will never try to publish, reuse, extend, or hunt for gnarly bugs, they work just fine like they did in almost every computer and programming language from 50+ years ago.
You can just take a reference to the view containing the bool and get the variable using a getter.
If you want app wide variables, you could put them in the AppDelegate, but I highly recommend against that since it tightly couples classes.
Create a data model class. Instantiate it in your app delegate, and pass it along to your view controllers. Use Key-Value Observing to track changes to the model in your view controllers. See my answer here: How do I display and calculate numbers from a database on iPhone?
"Why shouldn't I use globals? It can't hurt just this once." This is a bad habit to get into. Avoiding global variables makes your code easier to read and reuse, easier to extend, and easier to debug.

how to declare a variable as extern in objectivec,so that i can access that in any view controller

i want to access the same variable in all view controllers ....
extern is a C keyword, and works the same in Objective-C as in straight C. In your header file, declare your variable:
extern NSString *myGlobal;
And then set it in your .m file.
However, this is frequently a poor coding practice; it is generally preferable to explicitly hand your view controllers some kind of state object or data source.
Instead of putting in an extern for variables, store your data in the AppDelegate instance - or in some other singleton. Then you can get to it, and modify it, from anywhere.
While I'll admit I still use the AppDelegate solution quite often, I believe the singleton design pattern is a better solution. Here's a link to a solution and the reasoning.

How to make a Global Array?

So, I read this post, and it's pretty much exactly what I was looking for. However... it doesn't work. I guess I'm not going to go with the singleton object, but rather making the array in either a Global.h file, or insert it into the _Prefix file.
Both times I do that though, I get the error:
Expected specifier-qualifier-list before 'static'
and it doesn't work. So... I'm not sure how to get it to work, I can remove extern and it works, but I feel like I need that to make it a constant.
The end goal is to have this Mutable Array be accessible from any object or any file in my project. Help would be appreciated!
This is the code for my Globals.h file:
#import <Foundation/Foundation.h>
static extern NSMutableArray * myGlobalArray;
I don't think I need anything in the implementation file. If I were to put that in the prefix file, the error was the same.
EDIT
So, I removed the .m file from Globals, and I just have the code about in Globals.h. Assuming I am going to continue with this terrible practice of having global variables (I know it's bad, I just want to test this out), I now have a new error. It says:
"Multiple storage classes in declaration specifiers"
If I remove "extern" it works and if I remove "static" it works, but having both doesn't... what now?
****Double Edit****
Aright, so I've tried adding the array to my UIApplication Delegate, but I'm doing it wrong because it isn't working. Could someone give me some example code as to where to place it an access it? I don't know if it should go in the implementation, or somewhere else, and once the array is initialized how to access it from the other files... Do I set a new variable to the array, or something?
Just a general programming suggestion--don't share an array. You have no control over it and it will be virtually impossible to trace if something changes it at a time and in a way you aren't expecting.
Instead, create an object with the array inside it and make that object a singleton (or better yet, make a factory for it).
Whenever you want to modify your array, call methods on the object to do so. If you do this, I bet you will find a lot of redundant code you can factor into this object (for instance, searching the array for a value--make a "search" method in the object instead and pass in a value).
It may seem like a lot of work you shouldn't have to do, but you'll find it's fairly fun work, and you should find that you DO have to do it once you see how much code belongs in this object...
Just add the array as a property of the application delegate, and access it like:
[[UIApplication sharedApplication] myArray];
The two (main) ways of making an array global are separate -- either you have a class with a method
static NSMutableArray *foo;
+(NSMutableArray *)foo {
return foo;
}
(in the .m file) with the static piece NOT in the header file, or just
static extern NSMutableArray * myGlobalArray;
with out the singleton wrapper (which I think is better as it saves you from having an extra bit of unnecessary code)
Either way, it is still a bad practice that I would try to avoid.
In general, the presence of a "Globals.h" file is a bad smell that there's an antipattern at work.
I would even advise against Bill K's advice and not use a Singleton pattern at all.
Instead, create the array in your app delegate, and pass it to your root view controller(s), and along the hierarchy to the components that need access to it.
This is what I was looking for:
http://derekneely.com/tag/app-delegate/
Thank you for pointing me in the right direction!
#import <Foundation/Foundation.h>
static extern NSMutableArray * myGlobalArray;
#interface Globals : NSObject {
}
#end