我知道共享数据的一种方法是segue。但是在我的应用程序中,我有多个选项卡,其中包含许多VC。例如userName
和address
。我想在某些VC中显示这些信息。
每次我查询云都不正确。我正在遵循这个答案的第一部分:answer。但是作为一个新手,我不确定如何定义MyDataModel
。它是NSObject类吗?如果有人可以用两个NSString
字段将此类定义为示例,我将不胜感激。以及如何在VC和AppDelegate中访问这些字段。
内部AppDelegate
@interface MyAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate>
{
MyDataModel *model;
AViewController *aViewController;
BViewController *bViewController;
...
}
@property (retain) IBOutlet AViewController *aViewController;
@property (retain) IBOutlet BViewController *aViewController;
@end
@implementation MyAppDelegate
...
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
...
aViewController.model = model;
bViewController.model = model;
[window addSubview:tabBarController.view];
[window makeKeyAndVisible];
}
内部VC:
@interface AViewController : UIViewController {
MyDataModel *model;
}
@property (nonatomic, retain) MyDataModel *model;
@end
@interface BViewController : UIViewController {
MyDataModel *model;
}
@property (nonatomic, retain) MyDataModel *model;
@end
我唯一需要的是在哪里定义
MyDataMode
以及如何访问其字段? 最佳答案
您可以使用单例类,
----------
SharedManages.h
----------
#import <Foundation/Foundation.h>
#import "Reachability.h"
#import "Reachability.h"
@interface SharedManager : NSObject
{
}
+(SharedManager *)sharedInstance;
// Create property of your object which you want to access from whole over project.
@property (retain, nonatomic) User *loginUser;
@property (assign, readwrite) BOOL isNetAvailable;
@end
----------
----------
SharedManages.m
----------
#import "SharedManager.h"
static SharedManager *objSharedManager;
@implementation SharedManager
@synthesize
isNetAvailable = _isNetAvailable,
loginUser = _ loginUser;
+(SharedManager *)sharedInstance
{
if(objSharedManager == nil)
{
objSharedManager = [[SharedManager alloc] init];
objSharedManager. loginUser = [User alloc]] init];
Reachability *r = [Reachability reachabilityForInternetConnection];
NetworkStatus internetStatus = [r currentReachabilityStatus];
// Bool
if(internetStatus == NotReachable)
{
NSLog(@"Internet Disconnected");
objSharedManager.isNetAvailable = NO; // Internet not Connected
}
else if (internetStatus == ReachableViaWiFi)
{
NSLog(@"Connected via WIFI");
objSharedManager.isNetAvailable = YES; // Connected via WIFI
}
else if (internetStatus == ReachableViaWWAN)
{
NSLog(@"Connected via WWAN");
objSharedManager.isNetAvailable = YES; // Connected via WWAN
}
}
return objSharedManager;
}
@end
从其他 class 访问...
[SharedManager sharedInstance].isNetAvailable ;
[SharedManager sharedInstance].loginUser ;
希望这个能对您有所帮助..