views:

704

answers:

2

i want to access a integer and a string from a class to all the other classes? what is the best way to do it? i want to increase the values any where in the program and then want to update them in the class declared....

any idea how to achieve this???

+2  A: 

You could make the integer and string properties of your app delegate and pass references to the delegate around to your views. I do something like this myself, though to be honest it is a pain and also a little error prone to make the app delegate available to all the views.

Or (and this is probably better), you could declare a singleton class (google the singleton pattern) as one of your data classes, and have your integer/string be properties of that. Then you could access the getters/setters of your singleton from anywhere in your program. You will need to take extra care if you have multiple threads however,

frankodwyer
+5  A: 

Here's a question (and good answers) about singletons.

You could also use the app delegate, as frankodwyer suggested, and access it from anywhere using:

id delegate = [[UIApplication sharedApplication] delegate];

For ease of use and type safety I use a category like this:

// put his in your delegate header file
@interface UIApplication(MyAppAdditions)
+ (MyAppDelegate*)sharedDelegate;
@end

// put his in your delegate implementation file
@implementation UIApplication(MyAppAdditions)
+ (MyAppDelegate*)sharedDelegate {
    return (MyAppDelegate*)[[self sharedApplication] delegate];
}
@end

Now you can access your app delegate from everywhere: [UIApplication sharedDelegate]

Nikolai Ruhe
+1 nice - I didn't know there was a shortcut to get the delegate like that. I've been manually setting it as a property of views..doh!
frankodwyer
I like to do something similar, but with #define's instead, like so:#define UIApp [UIApplication sharedApplication]#define UIAppDelegate ((MyAppDelegate*)[UIApp delegate])
Dave DeLong
is there any other way?means i have one uitable which has 2 section.both section contains multiple rows.both section refers to two different views.i want to increment a integer in both views.and when i return back from table i want to update in database
Rahul Vyas
please post your code in more details.... and what if i do not want to use appdelegate. how to create global variables in other class and access them without creating class's instance
Rahul Vyas