2015-09-04 71 views
1

我知道共享數據的一種方法是繼續。但在我的應用程序中,我有多個包含VC數量的選項卡。例如userNameaddress。我想向一些風險投資家展示這些信息。我每次查詢雲時都是不正確的。我在回答第一部分:answer。但作爲新手,我不確定如何定義MyDataModel。它是一個NSObject類嗎?我很感激任何人都可以將這個類定義爲兩個NSString字段的例子。以及如何在VC和AppDelegate中訪問這些字段。如何在多個ViewControllers之間共享數據?

裏面的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以及如何訪問它的字段?

+0

創建一個NSObject的子類,並在.h文件中創建'@property(nonatomic,retain)NSString * str1;' '@property(nonatomic,retain)NSString * str2;' –

回答

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 ; 

希望,這將幫助你..

+0

感謝您的回答。所以你的意思是我的問題中的SharedManages等於SharedManages。我需要所有這些設置以及你在這裏給你的東西還是這個類? – Bernard

2

我沒有「本地」值的副本。我將它們放在代表中並從那裏取回。這樣你就不必在代表中硬編碼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的:

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,但很容易找)我能想到的是使用NSUserDefaults

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

how to get the delegate in obj-c

1

最簡單的方法。保存在您NSUserDefaultsnameaddress

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"]; 

希望這有助於。

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); 
相關問題