将appdelegate数据传递给viewcontroller

时间:2012-12-05 07:01:38

标签: iphone ios xcode uiviewcontroller

我的AppDelegate.m中有以下方法。我希望deviceToken

UIViewController的值为- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken { NSLog(@"My token is: %@", deviceToken); ViewController *viewController = [[ViewController alloc]initWithNibName:@"ViewController" bundle:nil]; viewController.tokenStr = [NSString stringWithFormat:@"%@",deviceToken]; }
NSLog(@"%@",tokenStr);

但是当我在UIViewController中显示(NULL)时,我正在UIViewController。 如何在{{1}}中获取值?

3 个答案:

答案 0 :(得分:3)

AppDelegate中,您可以将deviceToken值保存在NSUserDefaults

[[NSUserDefaults standardUserDefaults] setObject:deviceToken forKey:@"DeviceToken"];
[[NSUserDefaults standardUserDefaults] synchronize];

并使用

从任何View Controller中检索该值
[[NSUserDefaults standardUserDefaults] objectForKey:@"DeviceToken"];

答案 1 :(得分:1)

您可以使用[UIApplication sharedApplication].delegate引用AppDelegate。
这取决于你的需求。像真正应该保存在NSUserDefaults中的令牌,它是专为保存用户的凭据和令牌而设计的。但是如果你想在任何viewController中使用AppDelegate的所有公共属性和方法,你可以使用它的委托。

AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSString *token = appDelegate.token;

答案 2 :(得分:1)

在AppDelegate.m类中:

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSLog(@"My token is: %@", deviceToken);

    NSString *device = [deviceToken description];
    device = [device stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    device = [device stringByReplacingOccurrencesOfString:@" " withString:@""];

    NSLog(@"My device is: %@", device);

    [[NSUserDefaults standardUserDefaults] setObject:device forKey:@"MyAppDeviceToken"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

在ViewController类中,viewDidLoad方法内部:

    [super viewDidLoad];

    NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"MyAppDeviceToken"];
    NSLog(@"device token in controller: %@ ", deviceToken);

这在我的设备中完美运行。快乐编码!! :)