0

First off, I despise singletons with a passion. Though I should probably be trying to use one, I just don't want to. I want to create a data class (that is instantiated only once by a view controller on loading), and then using a different class, message the crap out of that data instance until it is brimming with so much data, it smiles.

So, how do I do that? I made a pointer to the instance of the data class when I instantiated it. I'm now over in a separate view controller, action occurs, and I want to update the initial data object. I think I need to reference that object by way of pointer, but I have no idea how to do that. Yes, I've set properties and getters and setters, which seem to work, but only in the initial view controller class.

4

6 回答 6

1

如果您不喜欢该模式或它不适合,则无需使用单例。假设您在第一个视图控制器中创建第二个视图控制器,只需在第二个视图控制器中为模型对象声明一个 ivar 和属性,然后在实例化它时,将模型对象分配给该属性。

于 2010-06-17T23:13:38.533 回答
0

不要忘记 Objective-C 是 C 的超集。

基本上,数据类是一个普通的 C struct

如果要从另一个类访问该类的变量,请将其设为全局变量。

我的数据.h:

struct MyData {
    // Whatever data fields that you need, e.g.:
    NSInteger value;
};

extern struct MyData mydata;

我的数据.c:

struct MyData mydata = {
    // Whatever initial value that you find relevant, e.g.:
    .value = 42;
};
于 2010-06-18T08:03:51.920 回答
0

Make a global variable for your object and store it there on creation. You can wire that up in the init method (probably bad style), or from the caller or via interface builder. Just make your variable known in the files that use it.

Or - well - use some kind of singleton pattern and get the instance directly from that class. Looks much cleaner.

于 2010-06-17T22:50:56.527 回答
0

认真使用单例。如果您不喜欢它们,因为您不知道代码:

@interface Order : NSObject {
NSMutableArray *order;
}

@property (nonatomic, retain) NSMutableArray *order;

+ (Order *)sharedInstance;

@end

#import "Order.h"


@implementation Order

@synthesize order;

+(Order *)sharedInstance {
static Order *myInstance = nil;

@synchronized(self) {
    if(!myInstance) {
        myInstance = [[Order alloc] init];
        }
    }
return myInstance;
}

-(void)dealloc {
    [order release];
    [super dealloc];

}
@end
于 2010-06-17T22:55:14.163 回答
0

嗯。你好。Core Data 对你来说不是一个足够好的框架吗?它允许您拥有一个持久存储和多个上下文来管理更新和合并更改以响应通知。我可能在这里不合时宜,但是看到您如何在第一个问题中以对公认模式的强烈观点开始问题,这表明您没有花费太多时间来发现 iOS 中的目标 c 运行时和 Foundation 类的方式可以协作完成任务。在任何软件中,一个对象且只有一个对象拥有特定资源。你应该接受单身人士。我建议你花点时间阅读 http://www.cocoadesignpatterns.com/。哦,是的,看看KVO的含义。

于 2010-06-18T03:55:00.337 回答
0

为什么不让它成为您的应用程序委托的属性?这样就不必使用单例模式,但您正在利用 Apple 已经存在的单例模式使用。

于 2010-06-18T07:53:03.990 回答