How to share an object with the entire project?

2019-08-25 20:35发布

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?

3条回答
混吃等死
2楼-- · 2019-08-25 21:02

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

查看更多
贼婆χ
3楼-- · 2019-08-25 21:13

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];
查看更多
淡お忘
4楼-- · 2019-08-25 21:16

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.

查看更多
登录 后发表回答