ios 單例模式

網(wǎng)絡(luò)信息

#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循環(huán)隨機,所以排列順序未知
//        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 -- 接收到的數(shù)據(jù)處理
+ (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)]
                          };
    
    //根據(jù)設(shè)備號分類發(fā)送通知
    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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 簡介: 單例模式是一種常用的軟件設(shè)計模式。在它的核心結(jié)構(gòu)中只包含一個被稱為單例類的特殊類。通過單例模式可以保證系統(tǒng)...
    RunnerFL閱讀 706評論 0 0
  • 單例模式保證程序的整個生命周期中,只會創(chuàng)建一個單例類的實例。 應(yīng)用,適用場景輕松實現(xiàn)兩個不同類之間的數(shù)據(jù)通信。 創(chuàng)...
    印林泉閱讀 213評論 0 1
  • 單例介紹 本文源碼下載地址 1.什么是單例 說到單例首先要提到單例模式,因為單例模式是單例存在的目的 單例模式是一...
    雷鳴1010閱讀 3,678評論 0 19
  • iOS設(shè)計模式——單例模式http://blog.csdn.net/lovefqing/article/detai...
    LV大樹閱讀 804評論 0 1
  • 單例在整個工程中相當于一個全局變量,無論在哪里需要用到這個類的實力變量,都可以通過單例方法來取得,而且一旦創(chuàng)建了一...
    Jalynn葸閱讀 245評論 0 1

友情鏈接更多精彩內(nèi)容