singleton in objective c

后端 未结 5 728
孤街浪徒
孤街浪徒 2021-01-22 08:56

I saw a singleton example on objective-c book. However, I don\'t know if there is difference of meaning of \'singleton\' definition between objective-c and other langs. Can this

5条回答
  •  旧时难觅i
    2021-01-22 09:45

    Singleton class is used to save the data for use anywhere in app.

    //SingletonObject
    #define saveDataSingletonObject ((SaveDataSingleton*)[SaveDataSingleton sharedManager])
    
    @interface SaveDataSingleton : NSObject
    
    @property (nonatomic,strong) NSMutableArray *DataArr;
    + (id)sharedManager;
    -(void)clearAllSaveData;
    
    @end
    
    @implementation SaveDataSingleton
    @synthesize DataArr;
    + (id)sharedManager {
        static SaveDataSingleton *sharedManager;
        if(!sharedManager) {
            @synchronized(sharedManager) {
                sharedManager = [SaveDataSingleton new];
            }
        }
        return sharedManager;
    }
    -(void)clearAllSaveData{
        DataArr=nil;
    }
    - (id)init {
        if (self = [super init]) {
            DataArr = [[NSMutableArray alloc]init];
        }
        return self;
    }
    // using setter getter save and retrieve data
    +(void)setDataArr:(NSMutableArray *)Dataarr
    {
        self.DataArr = [[NSMutableArray alloc]initWithArray:Dataarr];
    }
    
    +(NSMutableArray *)DataArr
    {
        return self.DataArr;
    }
    @end
    

    Save and Retrieve data // Use singleton Object

    // save data using setter function.
    [saveDataSingletonObject setDataArr:Array];
    //fetch data using getter function.
    NSArray *arr=[saveDataSingletonObject DataArr];
    

提交回复
热议问题