【问题标题】:Using multiple times appDelegate in the same UIViewController在同一个 UIViewController 中多次使用 appDelegate
【发布时间】:2012-12-11 10:55:33
【问题描述】:

我是 Objective-C 和 cocoa 的新手。

在我的 UIViewController 中,我需要以不同的方法多次访问 AppDelegate

A.正在调用每个方法:

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

消耗更多性能?

B.我试图在 UIViewController 中创建一个全局参数:

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

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

实现和使用:

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

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

但我收到警告(尽管代码有效)

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

appDelegate中businessId的声明为:

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

和实施:

@implementation AppDelegate
@synthesize businessId;

【问题讨论】:

    标签: iphone objective-c pointers nsinteger appdelegate


    【解决方案1】:

    从应用委托中的声明中删除 *

    @property NSInteger (assign) businessId;
    

    NSInteger 是原语,所以不需要对象指针。

    【讨论】:

    • 感谢工作正常。但是第一个问题呢?它会消耗性能吗?
    • 没有惩罚。没什么好担心的。
    • 最佳编码实践是什么?
    • 这是一种非常常见的模式。您还可以定义一个文本宏以加快输入速度,但这并没有太大的区别。存储程序范围变量的另一个流行且合理的选择是NSUserDefaults
    【解决方案2】:

    A.除非您将其称为每秒 100000000,否则这不会造成任何性能损失。顺便说一句,从不假设——总是衡量。有一个名为 Time Profiler 的工具 - 使用它来查找所有瓶颈。

    B. NSInteger 只是 int 的 typedef - 它是 POD 类型而不是 ObjC 对象,因此您不能向它发送消息。使用 NSInteger 而不是 NSInteger*。

    【讨论】:

      【解决方案3】:

      你可以这样定义 AppDelegate #define DELEGATE (AppDelegate *)[[UIApplication sharedApplication] delegate]; 现在您可以在需要的地方使用 DELEGATE..

      【讨论】:

      • 你可以在你使用所有常量的地方声明全局类或相同的类在这里也像这样 #import #import "AppDelegate.h" #define DELEGATE (AppDelegate * )[[UIApplication sharedApplication] 委托];
      • 谢谢 - 但如何在代码中使用它?我试图导入我的常量类并编写 APP_DELEGATE.shouldDo 但它不会编译
      猜你喜欢
      • 2014-03-02
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 2015-07-07
      • 2013-12-26
      • 1970-01-01
      相关资源
      最近更新 更多