2

I am new to objective-C and cocoa.

In my UIViewController I need to access AppDelegate multiple times in different methods

A. Is calling in every method:

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

consumes more performance?

B. I tried to create a global parameter in the UIViewController:

#import <UIKit/UIKit.h>
#import "AppDelegate.h"

@interface Login_ViewController : UIViewController<UITextFieldDelegate,UIImagePickerControllerDelegate>{
  AppDelegate *appDelegate;
}

Implementation and usage:

- (void)viewDidLoad
{
     appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];  
     appDelegate.businessId = [businessId integerValue]; 
}

- (BOOL)credentialsValidated
{
     appDelegate.businessId = [[NSUserDefaults standardUserDefaults] integerForKey:BUSINESS_ID];
}

But I get warning (although the code works)

Incompatible integer to pointer conversion assigning to 'NSInteger *' (aka 'int *') from 'NSInteger' (aka 'int'); 

The declaration of businessId in appDelegate is:

@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property NSInteger *businessId;

and the implementation:

@implementation AppDelegate
@synthesize businessId;
Dejell
  • 13,947
  • 40
  • 146
  • 229

3 Answers3

4

Remove the * from your declaration in the app delegate:

@property NSInteger (assign) businessId;

NSInteger is a primitive, so you do not need an object pointer.

Mundi
  • 79,884
  • 17
  • 117
  • 140
  • Thanks worked fine. but what about the first question? does it consume performance? – Dejell Dec 11 '12 at 11:13
  • No penalty. Nothing to worry about. – Mundi Dec 11 '12 at 11:14
  • what is the best coding practice? – Dejell Dec 11 '12 at 11:16
  • This is a very common pattern. You could also define a text macro for faster typing, but it does not really make a big difference. Another popular and reasonable option for storing program-wide variables is `NSUserDefaults`. – Mundi Dec 12 '12 at 05:40
1

A. This won't give any performance penalty unless you call it 100000000 a second. BTW never assume smth - always measure. There is a tool called Time Profiler - use it to find all the bottlenecks.

B. NSInteger is just a typedef to int - it is POD type and not ObjC object, so you can't send messages to it. Use NSInteger instead of NSInteger*.

Max
  • 16,679
  • 4
  • 44
  • 57
1

You can define AppDelegate like this #define DELEGATE (AppDelegate *)[[UIApplication sharedApplication] delegate]; now you can use DELEGATE where you need..

Ajeet
  • 157
  • 7
  • You can this where you are using all constant declare make Global class or same class here also like this #import #import "AppDelegate.h" #define DELEGATE (AppDelegate *)[[UIApplication sharedApplication] delegate]; – Ajeet Dec 16 '12 at 09:32
  • thanks - but how do I use it in the code? I tried to import my constants class and write APP_DELEGATE.shouldDo but it wouldn't compile – Dejell Dec 16 '12 at 15:26