On lazy instantiation and convenience methods

前端 未结 4 989
醉话见心
醉话见心 2020-12-18 15:43

Assume you have a Singleton Constants class, instance of which you\'d like to use throughout your application.

In someClass, therefore we

4条回答
  •  离开以前
    2020-12-18 16:43

    For constant I prefer to use a .h file like this

    // ConstanteDef.h
    #pragma mark Entity Name Constante
    #define kItemInfos @"ItemInfos"
    #define kCategorie_DItems @"Categorie_DItems"
    #define kCommerce @"Commerce"
    #define kListe @"Liste"
    #define kListeItem @"ListeItem"
    #define kPrixElement @"PrixElement"
    #define kTypeDe_CommerceOuListe @"TypeDe_CommerceOuListe"
    

    While I would use the Singleton to return me more complex element.
    Here is a singleton that I've made to simplify my live with core data, instead of rewriting the same code everywhere.

    @interface CoreDataController : NSObject {
    
    NSManagedObjectContext *leManagedObjectContext;
    NSManagedObjectModel *leManagedObjectModel;
    
    @private
    Commerce_MO *leCommerceAucun;
    }
    @property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
    @property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
    
    #pragma mark Objet par Défaut
    @property (nonatomic, retain, readonly) Commerce_MO *commerceAucun;
    
    #pragma mark Nouvel Objet
    //  new = retain count = 1, celui qui commande est responsable de la mémoire.
    - (id)newMOforClass:(Class)uneClasse;   //  Pas le mieux, mais pourrais servir pendant le run time.  Retourne nil si uneClasse ne correspond pas à quelque chose.
    - (PrixElement_MO *)newPrixElement;
    - (ItemInfos_MO *)newItemInfos;
    - (Commerce_MO *)newCommerce;
    - (Liste_MO *)newListe;
    - (ListeItem_MO *)newListeItem;
    
    #pragma mark Singleton call
    + (CoreDataController *)sharedCoreDataController;
    @end
    

    So in my code when I need to create a new entity I just need to do this :

    CoreDataController *cdc = [CoreDataController sharedCoreDataController];
    Liste_MO * = [cdc newListe];
    

    For more on the Singleton concept, Look HERE in the Apple documentation at the section Creating a Singleton Instance, and look closely at the code they are giving to make a singleton, that should answer your interrogation about weak or strong link to it.
    But in essence a strict singleton implementation will only have one instance of that class created for the whole duration of the application. So if you got 100 objects pointing to it doesn't change your memory foot print, there is only 1 singleton, but if you have thoses 100 objects that will definitely impact your memory.

提交回复
热议问题