开发者

need to define a "modifiable" global variable in objective-c

I have the following issue. I have two classes that manipulate information but they are completely disconnected, i.e. I can't reach the other class.

I need both classes to use a certain value. For example, class A sets the value foo = A and class B needs to be able to read that开发者_如何转开发 value and rest foo to nil.

I thought about creating the variable in the main app delegate, but can't figure out how.

Ideas?!!


Global variables are generally bad idea. Based on your description i think you can use KVO to inform class B about the changes in 'foo'.

But if you relly need a global variable you can do this:

@interface YourAppDelegate : NSObject <UIApplicationDelegate> {
}
@property (nonatomic) NSString *foo;
@end

@implementation YourAppDelegate
@synthesize foo;
...
@end


@implementation ClassA
...
- (void)someMethod {
YourAppDelegate *appDelegate = (YourAppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.foo = @"NewValueOfFoo";
}
...
@end


@implementation ClassB
...
- (void)otherMethod {
YourAppDelegate *appDelegate = (YourAppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(@"Value of foo: %@", appDelegate.foo);  //This will print: "Value of foo: NewValueOfFoo"
}
...
@end


I'm not sure what you mean by "completely disconnected". Depending on what you're trying to do, you could use NSUserDefaults

http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSUserDefaults_Class/Reference/Reference.html

or NSNotifications

http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSNotification_Class/Reference/Reference.html

If class A doesn't need to know about class B, you could consider delegation as well.


Why can't he just do this?

A. Add 2 new files to your project: GlobalValues.h and GloblaValues.m.

B. Open GlobalValues.h, and declare all your needed variables.

extern NSString *MyServiceName; // name of the 'service':

C. Open GlobalValues.m, and start the new file by importing GlobalValues.h, and assign values to the variables you declared in the header file:

#import "GlobalValues.h"

NSString *MyServiceName = @"MyService is called THIS";

D. In the implementation files of the classes that need to use these variables, you would put - at the very beginning:

#import "GlobalValues.h"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜