How to share an object with the entire project?

2019-08-25 20:32发布

问题:

For example, if I create an UILabel in an class, how can I use it wherever I want to?

I already know how to share between two classes. But I need to call the value of an object in all my classes. Is it possible?

回答1:

Is a singleton what you want? Basically a singleton is just a class that only returns the same instance no matter what. Here's a website that shows you how to do them. http://funwithobjc.tumblr.com/post/3478903440/how-i-do-my-singletons



回答2:

The best way is to write it to the temporary files folder like this:

NSString *pathtmp = [NSTemporaryDirectory() stringByAppendingPathComponent:@"tmpString.txt"];
NSString *stringToWrite = [NSString stringWithFormat:@"%@",Label.text];
[stringToWrite writeToFile:pathtmp atomically:YES encoding:NSStringEncodingConversionExternalRepresentation error:nil];

and to read it:

NSString *pathtmp = [NSTemporaryDirectory() stringByAppendingPathComponent:@"tmpString.txt"];
NSString *stringToWrite = [NSString stringWithContentsOfFile:pathtmp encoding:NSStringEncodingConversionExternalRepresentation error:nil];


回答3:

You asked that "I need to call the value of an object in all my classes. Is it possible?" and mentioned a UILabel.

You should really avoid view layer components poking at other view layer components. It creates coupling which makes it (1) really hard to change - simple changes break large areas of the code in unpredictable ways (see ref to spaggeti code above) and (2) hard to test since there's no layers in the system.

You should look into the principles of MVC. In MVC, you have views, controllers and models. You should push as much down as possible. Multiple views and controllers can operate on the same model that controls the data and business logic.

The model is the data and the operations you perform on the data. Make all you different views work off that data instead of poking at each other.

I would suggest create a set of model classes and to allow common access to that model. A common pattern is for that class to be a singleton.

So, the multiple views & controllers would do.

MyModel *model = [MyModel sharedInstance]; Then multiple controllers can operate on it.

Here's a good article on the topic: http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html

singleton from apple: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW32

Hope that helps.