繁体   English   中英

在Objective-C中共享数据对象的最佳方法是什么?

[英]What is the optimal way to share data objects in Objective-C?

我不知道我是否做得正确。 我正在开发一个大型应用程序,用户必须在其中登录并与各种功能和数据进行交互。 有许多视图控制器需要访问此用户对象。

以下代码段是用户登录的时刻,现在我有了一个可在我的应用程序中使用的用户对象。 在这种情况下,我使用的是伪数据。

User *user = [User new];
[user setupTempOfflineData];

self.newViewController.user = user;

[self containerAddChildViewController:self.newViewController];

在newViewController中是属性:

@property (nonatomic, strong) User *user;

现在,NewViewController可能有许多子代,而那些子代拥有自己的视图控制器。 所有这些都为用户提供了强有力的参考。 用户创建的其他信息(例如注册组列表或内容)也将保留。 有时,我要么通过用户对象访问下载的信息,要么只是存储和共享对数组/数据本身的引用。

我脑子里有些东西告诉我,我应该使用单例或其他我不熟悉的设计模式。 因此带我来问这个问题:

我这样做对吗?

编辑: KVO上的信息链接

您可以在User类上使用单例模式。 例如

User.h文件

@interface User : NSObject

+ (User*)currentUser;

//...
// Some properties
//...

//...
// Some methods
//...

@end

User.m文件

//...
+ (User*)currentUser
{
    static User *user = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        user = [[self alloc] init];
    });

    return user;
}
//...

在您的.pch文件中导入“ User.h”文件。

现在,您可以通过调用来访问用户对象
[User currentUser];

我在应用程序中使用Singleton模式,并使用惰性实例化加载该用户。

因此,在您的newViewController.m中

/**
  * lazy instantiation of User
 */
- (User *) user {
    if (!_user){
        _user = [User getUser];
    }
    return _user;
}

在User.h中

@interface User : NSObject

/**
 * Singleton
 */
+ (User *) getUser;

@end

最后在您的User.m中

#import "User.h"

/*
 * Singleton
 */
static User *singletonUser = nil;

@implementation User

/**
 * Designated initializer
 */
- (id) init {
    self = [super init];
    if (self != nil) {
        // Load your user from storage / CoreData / etc.
        [self setupTempOfflineData];
    }
    return self;
}

/**
 * Singleton
 */
+ (User *) getUser {
    if (singletonUser == nil) {
        singletonUser = [[self alloc] init];
    }
    return singletonUser;
}
@end

因此,现在您可以在NewViewController中使用self.user。

您正在做的事情应该可以工作。 您还考虑过协议和委托吗? 如果希望当User对象更改时通知NewViewController(或其他视图控制器)(KVO / Notificaiton是另一种设计模式),则可能需要考虑此设计模式。

用户名

@class User;
@protocol userProtocol <NSObject>
-(void) userObjectDidGetUpdated:(User*) u;
@end
@interface User:NSObject {}
@property (nonatomic,weak) id <userProtocol> delegate; // use weak here to prevent reference cycle
@end

User.m-当您要通知委托以获取更新的User对象时,请调用notifyDelegatesUserObjectHasChanged

@implementation
@synthesize delegate;
-(void) notifyDelegatesUserObjectHasChanged {
    [[self delegate] userObjectDidGetUpdated:self];
}
@end

现在,您可以注册视图控制器以获取更新的User对象,如下所示...

NewViewController.h

#import "User.h"
@interface NewViewController:UIViewController <userProtocol> {}

NewViewController.m

@implementation
-(void) userObjectDidGetUpdated:(User*) u {
    // this callback method will get called when the User object changes
}
@end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM