3

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???

Welbog
  • 59,154
  • 9
  • 110
  • 123
Rahul Vyas
  • 28,260
  • 49
  • 182
  • 256

2 Answers2

5

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]

Community
  • 1
  • 1
Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • +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 Jul 03 '09 at 12:00
  • I like to do something similar, but with #define's instead, like so: #define UIApp [UIApplication sharedApplication] #define UIAppDelegate ((MyAppDelegate*)[UIApp delegate]) – Dave DeLong Jul 03 '09 at 15:07
  • 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 Jul 07 '09 at 01:36
  • 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 Jul 08 '09 at 03:05
2

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
  • 13,948
  • 9
  • 50
  • 70