ios 单例模式

网络信息

#import <Foundation/Foundation.h>

@interface NetworkInfo : NSObject

@property (nonatomic, strong) NSMutableDictionary *localInfoDic;
@property (nonatomic, strong) NSMutableDictionary *webInfoDic;
@property (nonatomic, strong) NSMutableDictionary *rcuInfoDic;
@property (nonatomic, strong) NSMutableDictionary *userInfoDic;

+ (instancetype)sharedNetworkInfo;
- (BOOL)networkInfoDictionaryWriteToLocatedFile;


@end

#import "NetworkInfo.h"

@interface NetworkInfo ()
@property (nonatomic, strong) NSMutableDictionary *networkInfoDic;
@property (nonatomic, copy)   NSString            *networkInfoDicPlistPath;

@property (nonatomic, copy)   NSString            *currentIpAddress;

@end

@implementation NetworkInfo

#pragma mark - lazy load
- (NSString *)currentIpAddress{
    if (!_currentIpAddress) {
        NSString *address = @"error";
        struct ifaddrs *interfaces = NULL;
        struct ifaddrs *temp_addr = NULL;
        int success = 0;
        // retrieve the current interfaces - returns 0 on success
        success = getifaddrs(&interfaces);
        if (success == 0) {
            // Loop through linked list of interfaces
            temp_addr = interfaces;
            while(temp_addr != NULL) {
                if(temp_addr->ifa_addr->sa_family == AF_INET) {
                    // Check if interface is en0 which is the wifi connection on the iPhone
                    if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                        // Get NSString from C String
                        address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                    }
                }
                temp_addr = temp_addr->ifa_next;
            }
        }
        // Free memory  
        freeifaddrs(interfaces);  
        _currentIpAddress = address;
    }
    return _currentIpAddress;
}

- (NSString *)networkInfoDicPlistPath{
    if (!_networkInfoDicPlistPath) {
        NSArray *documentDirectoryArray = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
        NSString *myDocumentDirectory = [documentDirectoryArray firstObject];
        _networkInfoDicPlistPath = [myDocumentDirectory stringByAppendingPathComponent:@"NetworkInfoDic.plist"];
    }

    return _networkInfoDicPlistPath;
}

- (NSMutableDictionary *)NetworkInfoDic{
    if (!_networkInfoDic) {
        _networkInfoDic = [NSMutableDictionary dictionaryWithContentsOfFile:self.networkInfoDicPlistPath];
        if (!_networkInfoDic) {
            NSFileManager *fileManager = [NSFileManager defaultManager];
            [fileManager createFileAtPath:self.networkInfoDicPlistPath contents:nil attributes:nil];
            NSDictionary *dic = [NSDictionary dictionary];
            [dic writeToFile:self.networkInfoDicPlistPath atomically:YES];
            //_networkInfoDic = [NSMutableDictionary dictionaryWithContentsOfFile:self.networkInfoDicPlistPath];
        }
    }
    return _networkInfoDic;
}

- (NSMutableDictionary *)localInfoDic{
    if (!_localInfoDic) {
        _localInfoDic = [[NSMutableDictionary alloc] initWithDictionary:[self.networkInfoDic objectForKey:@"localInfo"]];
        //local ip reset
        [_localInfoDic setObject:self.currentIpAddress forKey:@"localIp"];
    }
    return _localInfoDic;
}
- (NSMutableDictionary *)webInfoDic{
    if (!_webInfoDic) {
        _webInfoDic = [[NSMutableDictionary alloc] initWithDictionary:[self.networkInfoDic objectForKey:@"webInfo"]];
    }
    return _webInfoDic;
}
- (NSMutableDictionary *)rcuInfoDic{
    if (!_rcuInfoDic) {
        _rcuInfoDic = [[NSMutableDictionary alloc] initWithDictionary:[self.networkInfoDic objectForKey:@"rcuInfo"]];
    }
    return _rcuInfoDic;
}
- (NSMutableDictionary *)userInfoDic{
    if (!_userInfoDic) {
        _userInfoDic = [[NSMutableDictionary alloc] initWithDictionary:[self.networkInfoDic objectForKey:@"userInfo"]];
    }
    return _userInfoDic;
}

#pragma mark-creating once
static NetworkInfo *sharedNetworkInfo = nil;

+ (instancetype)sharedNetworkInfo{
    return [[self alloc] init];
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedNetworkInfo = [super allocWithZone:zone];
    });
    return sharedNetworkInfo;
}

- (instancetype)init{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedNetworkInfo = [super init];
    });
    return sharedNetworkInfo;
}

- (id)copyWithZone:(NSZone *)zone{
    return  sharedNetworkInfo;
}
+ (id)copyWithZone:(struct _NSZone *)zone{
    return  sharedNetworkInfo;
}
+ (id)mutableCopyWithZone:(struct _NSZone *)zone{
    return sharedNetworkInfo;
}
- (id)mutableCopyWithZone:(NSZone *)zone{
    return sharedNetworkInfo;
}

#pragma mark - method
- (BOOL)networkInfoDictionaryWriteToLocatedFile{
    [self.networkInfoDic setObject:self.localInfoDic forKey:@"localInfo"];
    [self.networkInfoDic setObject:self.webInfoDic forKey:@"webInfo"];
    [self.networkInfoDic setObject:self.rcuInfoDic forKey:@"rcuInfo"];
    [self.networkInfoDic setObject:self.userInfoDic forKey:@"userInfo"];
    
    if ([self.networkInfoDic writeToFile:self.networkInfoDicPlistPath atomically:YES]){
        return true;
    }else{
        return false;
    }
    
}
//- (BOOL)isEqualToTheCurrentIpAddressWithIpAddress:(NSString *)ipAddress{
//    return [self.currentIpAddress isEqualToString:ipAddress];
//}

@end


@@@@@@@@@@@eg:事件处理中心@@@@@@@@@


#import <Foundation/Foundation.h>

@interface EPCore : NSObject

+ (instancetype)sharedEPCore;

+ (void) buttonClickedProcessingWithInfoDictionary:(NSDictionary *)infoDic;
+ (void) receiveDataProcessingWithData:(NSData *)data;
@end

#import "EPCore.h"

@implementation EPCore

#pragma mark-creating once
static EPCore *sharedEPCore;

+ (instancetype)sharedEPCore{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedEPCore = [[self alloc] init];
    });
    return sharedEPCore;
}

#pragma mark -- 按钮点击处理
+ (void)buttonClickedProcessingWithInfoDictionary:(NSDictionary *)infoDic{
    

    //得到字典中所有的key
    NSEnumerator *enumeratorkey=[infoDic keyEnumerator];
//    //得到字典中所有的value
//    NSEnumerator *enumeratorvalue=[infoDic objectEnumerator];
    NSMutableDictionary *mutInfoDic = [[NSMutableDictionary alloc] init];
    for (NSObject *obj in enumeratorkey) {
        //for循环随机,所以排列顺序未知
//        string = [NSString stringWithFormat:@"%@%@", string, [self oneCharacterToDoubleCharacter:(NSString *)obj]];
        [mutInfoDic setValue:[self oneCharacterToDoubleCharacter:[infoDic objectForKey:obj]] forKey:(NSString *)obj];
 
        
    }
    
    NSString *string = [NSString stringWithFormat:@"%@%@%@%@"
                        , [mutInfoDic objectForKey:@"equipmentNum"]
                        , [mutInfoDic objectForKey:@"viewNum"]
                        , [mutInfoDic objectForKey:@"buttonNum"]
                        , [mutInfoDic objectForKey:@"state"]
                        ];
    NSLog(@"%@", string);
    [[UDPNetwork sharedUDPNetwork] sendDataToRCU:[NSData dataWithBytes:&string length:string.length]];
}

//测试,小于10的编号前面加0
+ (NSString *)oneCharacterToDoubleCharacter:(NSString *)oneStr{
    if (oneStr.length < 2) {
        return [NSString stringWithFormat:@"0%@",oneStr];
    }else{
        return oneStr;
    }
}

#pragma mark -- 接收到的数据处理
+ (void)receiveDataProcessingWithData:(NSData *)data{
    NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    if (dataStr.length != 8) {
        NSLog(@"The data format is wrong !");
        return;
    }
    
    NSDictionary *dic = @{@"equipmentNum":[dataStr substringWithRange:NSMakeRange(0, 2)]
                          , @"viewNum":[dataStr substringWithRange:NSMakeRange(2, 2)]
                          , @"buttonNum":[dataStr substringWithRange:NSMakeRange(4, 2)]
                          , @"state":[dataStr substringWithRange:NSMakeRange(6, 2)]
                          };
    
    //根据设备号分类发送通知
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    switch ([dic[@"equipmentNum"] integerValue]) {
        case 1:
            [defaultCenter postNotificationName:@"LightsControllerNotification" object:nil userInfo:dic];
            break;
        case 2:
            [defaultCenter postNotificationName:@"AirconControllerNotification" object:nil userInfo:dic];
            break;
        case 3:
            [defaultCenter postNotificationName:@"ServerControllerNotification" object:nil userInfo:dic];
            break;
            
        default:
            break;
    }
    
}

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 简介: 单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统...
    RunnerFL阅读 3,851评论 0 0
  • 单例模式保证程序的整个生命周期中,只会创建一个单例类的实例。 应用,适用场景轻松实现两个不同类之间的数据通信。 创...
    印林泉阅读 1,468评论 0 1
  • 单例介绍 本文源码下载地址 1.什么是单例 说到单例首先要提到单例模式,因为单例模式是单例存在的目的 单例模式是一...
    雷鸣1010阅读 8,927评论 0 19
  • iOS设计模式——单例模式http://blog.csdn.net/lovefqing/article/detai...
    LV大树阅读 4,042评论 0 1
  • 单例在整个工程中相当于一个全局变量,无论在哪里需要用到这个类的实力变量,都可以通过单例方法来取得,而且一旦创建了一...
    Jalynn葸阅读 1,598评论 0 1

友情链接更多精彩内容