Reputation: 24750
I'm trying to wrap my head around singletons and I understand that the App Delegate is essentially a singleton object. I'm trying have some member variables in App Delegate that I can access from any other class. I did this in the App Delegate:
@interface AppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
RootViewController *viewController;
int screenwidth;
}
@property (nonatomic, retain) UIWindow *window;
@property (nonatomic) int screenwidth;
Then in the .m I did this:
- (void) applicationDidFinishLaunching:(UIApplication*)application
{
...
screenwidth=400; //arbitrary test number
Now I have another class in the project, and it does this in the .h:
#import "AppDelegate.h"
In the .m I have this somewhere:
test=(AppDelegate*)[[[UIApplication sharedApplication] delegate] screenwidth];
However, it claims that "screenwidth" is an instance method that is not found. I also tried this:
test=(AppDelegate*)[[UIApplication sharedApplication] delegate].screenwidth;
This uses the dot syntax since screenwidth
was synthesized, but it claims that property screenwidth not found
I'm sure these are basic issues that can be corrected simply. Any help appreciated.
Upvotes: 2
Views: 2778
Reputation: 488
If you want to avoid casting to your AppDelegate class every time, I recommend the following:
In MyAppDelegate.h
:
@interface MyAppDelegate : NSObject <UIApplicationDelegate>
+ (MyAppDelegate *)sharedAppDelegate;
@property (nonatomic) int screenwidth;
/* ... */
@end
In MyAppDelegate.m
:
@implementation LcAppDelegate
+ (MyAppDelegate *)sharedAppDelegate
{
return (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
}
/* ... */
@end
Of course, you still need to #import "MyAppDelegate.h"
in the files where you want to access it:
#import "MyAppDelegate.h"
/* ... */
NSLog(@"the apps screen width: %d", [MyAppDelegate sharedAppDelegate].screenwidth);
BTW, note that you should not use int
's and the like in Objective-C code. Instead, use NSInteger
, NSUInteger
, CGFloat
and so on.
Upvotes: 0
Reputation: 124997
Make sure that you're either providing your own -screenwidth
accessor or using the @synthesize
directive to get the compiler to provide one:
@synthesize screenwidth
The @property
directive is just a promise that accessors for the screenwidth
property will be provided. You still have to provide them as described above.
Upvotes: 1
Reputation: 14446
Consider trying:
test=[(AppDelegate*)[[UIApplication sharedApplication] delegate] screenwidth];
I think your two tries are trying to cast the .screenwidth
result to an AppDelegate*
.
Upvotes: 3