简体   繁体   中英

Creating another instance of a singleton class in Objective C

I have a singleton class which is being used throughout the app. I am working on another class that needs to send data to this singleton class, but can send data in bunch which will freeze the main thread.

Should I create another instance of this singleton class or should I should I create a data import utility as a separate class?

Singletons, as the name implies, are meant to have only a single instance floating around. Data freezing the main thread should be dispatched, another instance of a class won't help that.

Create another instance all you want, but don't call it singleton anymore.

Actually you should send this data in another thread and maybe use an NSLock while the data is being sent so you don't have any access errors.

Use:

[self performSelectorOnBackGround:@selector(sendDataToSingleton:) withObject:@"data to send"];

Don't create another instance of the singleton class or the rest of your application won't have access to it since it's a singleton.

Hope it helps.

By definition you should only have 1 instance of a singleton. If it's a properly constructed singleton it should not be possible to have more than 1!

If you are running into issues where your main thread is unresponsive, break the data you need to load into smaller chucks. This way, in between loading different chunks of data, the main thread can process any events it needs to and other objects can access the data in the singleton.

You could also implement a lazy data loading mechanism, where when an object wants information from the singleton, the singleton checks if your new class is waiting to give it new information and then loads it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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