单例类的实现

单例类:大概理解为只有一个对象的类,无论怎么创建都只有会分配一个内存

这几天,需要实现某个功能,而且在很多的类里面都要调用这个方法,所以我索兴就封装了一个类,直接调用这个类里面的方法就可以实现了,不需要每次都去写同一个方法(这是大背景),之后在在调用的时候我又发现我需要每次都要用同一个对象(重点来了),所以我才需要封装一个单例的类,而且这样不会浪费内存。

好了,直接上代码了:

+(UIView*)initActivityIndictionView

{

    static UIView *view = nil;

    static dispatch_once_t predicted;

    dispatch_once(&predicted ,^{

        view = [[self alloc]init];

        view.bounds = CGRectMake(0, 0, kScreenWidth, 100);

        view.center = CGPointMake(kScreenWidth/2, 50);

        

        UIActivityIndicatorView *testActivityIndicator = [[UIActivityIndicatorView    alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];

        testActivityIndicator.center = CGPointMake(kScreenWidth/2 - 60, 50);

        testActivityIndicator.bounds = CGRectMake(0, 0, 50, 50);

        [testActivityIndicator startAnimating];

        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth/2 - 30, 25, 120, 50)];

        label.text = @"正在拼命加载中...";

        label.font = [UIFont systemFontOfSize:14];

        

        [view addSubview:testActivityIndicator];

        [view addSubview:label];

    });

    return view;

}

 以上就是我自己封装的一个单例类,检验的话可以多创建几个对象,打印(%p)内存就可以了

原文地址:https://www.cnblogs.com/110-913-1025/p/5001501.html