如何在ViewControllers的数量之间共享数据?

时间:2015-09-04 03:24:40

标签: ios objective-c iphone

我知道分享数据的一种方法是segue。但在我的应用程序中,我有多个选项卡,其中包含许多VC。例如userNameaddress。我想在一些风险投资中展示这些信息。 每次我查询云都不对。我正在按照这个答案的第一部分: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的位置以及如何访问其字段?

4 个答案:

答案 0 :(得分:3)

你可以使用单身类,

----------
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

从其他类访问...

[SharedManager sharedInstance].isNetAvailable ;

[SharedManager sharedInstance].loginUser ;

希望,这会帮助你..

答案 1 :(得分:2)

我没有&#34;本地&#34;价值的副本。我在委托中设置它们并从那里获取它们。这样,您就不必为代理中的所有UIViewController代码进行硬编码。

最好在第一个视图或默认值上分配值。我个人使用viewDidLoad来做这些事情。因为它只在第一个视图上调用一次并且属于应用程序终止。

然后我从VC内部获取委托,调用实例并从那里调用值。

夫特

内部AppDelegate:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var globals : GlobalValueClass?

第一个VC:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
        delegate.globals = GlobalValueClass()
        delegate.globals!.numbers = [1,2,3]
    }
}

其他VC&#39>:

class ViewControllerTwo: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let delegate = UIApplication.sharedApplication().delegate as! AppDelegate

        print(delegate.globals!.numbers)
        // Do any additional setup after loading the view.
    }
}

目标C(在obj-c中没有完整的方法,但很容易找到)

MainClass *appDelegate = (MainClass *)[[UIApplication sharedApplication] delegate];

how to get the delegate in obj-c

答案 2 :(得分:1)

我能想到的最简单方法是使用NSUserDefaults。将您的nameaddress字符串保存在NSUserDefaults

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:YourNameString forKey:@"NameString"];
[defaults setValue:YourAddressString forKey:@"AddressString"];
[defaults synchronize];

并在任何ViewController

中访问它
 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
 NSString *name = [plistContent valueForKey:@"NameString"];
 NSString *address= [plistContent valueForKey:@"AddressString"];

希望这有帮助。

答案 3 :(得分:0)

您可以创建一个类并在标签控制器中使用它。

#import <Foundation/Foundation.h>



@interface UserModel : NSObject <NSCoding>

@property (nonatomic, strong) NSString *lastName;
@property (nonatomic, strong) NSString *firstName;

+ (instancetype)modelObjectWithDictionary:(NSDictionary *)dict;
- (instancetype)initWithDictionary:(NSDictionary *)dict;
- (NSDictionary *)dictionaryRepresentation;

@end

实施档案

#import "UserModel.h"


NSString *const kUserModelLastName = @"LastName";
NSString *const kUserModelFirstName = @"FirstName";


@interface UserModel ()

- (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict;

@end

@implementation UserModel

@synthesize lastName = _lastName;
@synthesize firstName = _firstName;


+ (instancetype)modelObjectWithDictionary:(NSDictionary *)dict
{
    return [[self alloc] initWithDictionary:dict];
}

- (instancetype)initWithDictionary:(NSDictionary *)dict
{
    self = [super init];

    // This check serves to make sure that a non-NSDictionary object
    // passed into the model class doesn't break the parsing.
    if(self && [dict isKindOfClass:[NSDictionary class]]) {
            self.lastName = [self objectOrNilForKey:kUserModelLastName fromDictionary:dict];
            self.firstName = [self objectOrNilForKey:kUserModelFirstName fromDictionary:dict];

    }

    return self;

}

- (NSDictionary *)dictionaryRepresentation
{
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
    [mutableDict setValue:self.lastName forKey:kUserModelLastName];
    [mutableDict setValue:self.firstName forKey:kUserModelFirstName];

    return [NSDictionary dictionaryWithDictionary:mutableDict];
}

- (NSString *)description 
{
    return [NSString stringWithFormat:@"%@", [self dictionaryRepresentation]];
}

#pragma mark - Helper Method
- (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict
{
    id object = [dict objectForKey:aKey];
    return [object isEqual:[NSNull null]] ? nil : object;
}


#pragma mark - NSCoding Methods

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];

    self.lastName = [aDecoder decodeObjectForKey:kUserModelLastName];
    self.firstName = [aDecoder decodeObjectForKey:kUserModelFirstName];
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{

    [aCoder encodeObject:_lastName forKey:kUserModelLastName];
    [aCoder encodeObject:_firstName forKey:kUserModelFirstName];
}

在您设置或初始化数据或值的位置导入此类。并在代码下面做。

    NSDictionary *dicUserModel = [[NSDictionary alloc]initWithObjectsAndKeys:@"Moure",@"LastName",@"Jackson",@"FirstName", nil];

    UserModel *userModel = [[UserModel alloc]initWithDictionary:dicUserModel];
    //NSUserDefault save your class with all property. and you can simply retrieve your UserModel from NSUserDefault.
    //Below code save this model into nsuserdefault.
    [[NSUserDefaults standardUserDefaults]setObject:[NSKeyedArchiver archivedDataWithRootObject:userModel] forKey:@"UserModel"];
    [[NSUserDefaults standardUserDefaults]synchronize];

您可以使用以下代码检索您的类对象。

    UserModel *savedUserModel = (UserModel *)[NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults]objectForKey:@"UserModel"]];
    NSLog(@"%@",savedUserModel.firstName);
    NSLog(@"%@",savedUserModel.lastName);