FLEX 學(xué)習(xí)筆記(一)

SystemLog 模塊

該方式可以獲取系統(tǒng)的log內(nèi)容
PS:但是不知道為什么,該方式獲取的log不完全是我們控制臺輸出的內(nèi)容艳汽,求解?

NSArray* AMKSystemLogMessages() {
    asl_object_t query = asl_new(ASL_TYPE_QUERY);

    // Filter for messages from the current process. Note that this appears to happen by default on device, but is required in the simulator.
    NSString *pidString = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]];
    asl_set_query(query, ASL_KEY_PID, [pidString UTF8String], ASL_QUERY_OP_EQUAL);

    aslresponse response = asl_search(NULL, query);
    aslmsg aslMessage = NULL;

    NSMutableArray *systemLogMessages = [NSMutableArray array];
    while ((aslMessage = asl_next(response))) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];

        NSString *timestamp = [NSString stringWithCString:asl_get(aslMessage, ASL_KEY_TIME)?:"" encoding:NSUTF8StringEncoding];
        if (timestamp.length) {
            NSTimeInterval timeInterval = timestamp.integerValue;
            NSString *nanoseconds = [NSString stringWithCString:asl_get(aslMessage, ASL_KEY_TIME_NSEC)?:"" encoding:NSUTF8StringEncoding];
        if (nanoseconds.length) timeInterval += nanoseconds.doubleValue / NSEC_PER_SEC;
            dict[@"date"] = [NSDate dateWithTimeIntervalSince1970:timeInterval];
        }

        dict[@"sender"] = [NSString stringWithCString:asl_get(aslMessage, ASL_KEY_SENDER)?:"" encoding:NSUTF8StringEncoding];
        dict[@"text"] = [NSString stringWithCString:asl_get(aslMessage, ASL_KEY_MSG)?:"" encoding:NSUTF8StringEncoding];
        dict[@"ID"] = [NSString stringWithCString:asl_get(aslMessage, ASL_KEY_MSG_ID)?:"" encoding:NSUTF8StringEncoding];
        [systemLogMessages addObject:dict];
    }
    asl_release(response);

    return systemLogMessages;
}

Network 模塊

字節(jié)數(shù)的轉(zhuǎn)化為字符串

例子

long long bytes = 18237019123;
NSString *bytesText = [NSByteCountFormatter stringFromByteCount:bytes countStyle:NSByteCountFormatterCountStyleBinary];
NSLog(@"%@", bytesText);    //  輸出: 16.98 GB

NSByteCountFormatter.h

/*  NSByteCountFormatter.h
Copyright (c) 2012-2015, Apple Inc. All rights reserved.
*/

#import <Foundation/NSFormatter.h>

NS_ASSUME_NONNULL_BEGIN

typedef NS_OPTIONS(NSUInteger, NSByteCountFormatterUnits) {
// This causes default units appropriate for the platform to be used. Specifying any units explicitly causes just those units to be used in showing the number.
NSByteCountFormatterUseDefault      = 0, 
//  Specifying any of the following causes the specified units to be used in showing the number.
NSByteCountFormatterUseBytes        = 1UL << 0, 
NSByteCountFormatterUseKB           = 1UL << 1,
NSByteCountFormatterUseMB           = 1UL << 2,
NSByteCountFormatterUseGB           = 1UL << 3, 
NSByteCountFormatterUseTB           = 1UL << 4, 
NSByteCountFormatterUsePB           = 1UL << 5, 
NSByteCountFormatterUseEB           = 1UL << 6, 
NSByteCountFormatterUseZB           = 1UL << 7, 
NSByteCountFormatterUseYBOrHigher   = 0x0FFUL << 8, 
// Can use any unit in showing the number.
NSByteCountFormatterUseAll          = 0x0FFFFUL 
};

typedef NS_ENUM(NSInteger, NSByteCountFormatterCountStyle) {
// Specifies display of file or storage byte counts. The actual behavior for this is platform-specific; on OS X 10.8, this uses the decimal style, but that may change over time.
NSByteCountFormatterCountStyleFile   = 0,        
// Specifies display of memory byte counts. The actual behavior for this is platform-specific; on OS X 10.8, this uses the binary style, but that may change over time.
NSByteCountFormatterCountStyleMemory = 1,
// The following two allow specifying the number of bytes for KB explicitly. It's better to use one of the above values in most cases.
NSByteCountFormatterCountStyleDecimal = 2,    // 1000 bytes are shown as 1 KB
NSByteCountFormatterCountStyleBinary  = 3     // 1024 bytes are shown as 1 KB
};


NS_CLASS_AVAILABLE(10_8, 6_0)
@interface NSByteCountFormatter : NSFormatter {
@private
unsigned int _allowedUnits;
char _countStyle;
BOOL _allowsNonnumericFormatting, _includesUnit, _includesCount, _includesActualByteCount, _adaptive, _zeroPadsFractionDigits;
int _formattingContext;
int _reserved[5];
}

/* Shortcut for converting a byte count into a string without creating an NSByteCountFormatter and an NSNumber. If you need to specify options other than countStyle, create an instance of NSByteCountFormatter first.
*/
+ (NSString *)stringFromByteCount:(long long)byteCount countStyle:(NSByteCountFormatterCountStyle)countStyle;

/* Convenience method on stringForObjectValue:. Convert a byte count into a string without creating an NSNumber.
*/
- (NSString *)stringFromByteCount:(long long)byteCount;

/* Specify the units that can be used in the output. If NSByteCountFormatterUseDefault, uses platform-appropriate settings; otherwise will only use the specified units. This is the default value. Note that ZB and YB cannot be covered by the range of possible values, but you can still choose to use these units to get fractional display ("0.0035 ZB" for instance).
*/
@property NSByteCountFormatterUnits allowedUnits;

/* Specify how the count is displayed by indicating the number of bytes to be used for kilobyte. The default setting is NSByteCountFormatterFileCount, which is the system specific value for file and storage sizes.
*/ 
@property NSByteCountFormatterCountStyle countStyle;

/* Choose whether to allow more natural display of some values, such as zero, where it may be displayed as "Zero KB," ignoring all other flags or options (with the exception of NSByteCountFormatterUseBytes, which would generate "Zero bytes"). The result is appropriate for standalone output. Default value is YES. Special handling of certain values such as zero is especially important in some languages, so it's highly recommended that this property be left in its default state.
*/
@property BOOL allowsNonnumericFormatting;

/* Choose whether to include the number or the units in the resulting formatted string. (For example, instead of 723 KB, returns "723" or "KB".) You can call the API twice to get both parts, separately. But note that putting them together yourself via string concatenation may be wrong for some locales; so use this functionality with care.  Both of these values are YES by default.  Setting both to NO will unsurprisingly result in an empty string.
*/
@property BOOL includesUnit;
@property BOOL includesCount;

/* Choose whether to parenthetically (localized as appropriate) display the actual number of bytes as well, for instance "723 KB (722,842 bytes)".  This will happen only if needed, that is, the first part is already not showing the exact byte count.  If includesUnit or includesCount are NO, then this setting has no effect.  Default value is NO.
*/
@property BOOL includesActualByteCount;

/* Choose the display style. The "adaptive" algorithm is platform specific and uses a different number of fraction digits based on the magnitude (in 10.8: 0 fraction digits for bytes and KB; 1 fraction digits for MB; 2 for GB and above). Otherwise the result always tries to show at least three significant digits, introducing fraction digits as necessary. Default is YES.
*/
@property (getter=isAdaptive) BOOL adaptive;

/* Choose whether to zero pad fraction digits so a consistent number of fraction digits are displayed, causing updating displays to remain more stable. For instance, if the adaptive algorithm is used, this option formats 1.19 and 1.2 GB as "1.19 GB" and "1.20 GB" respectively, while without the option the latter would be displayed as "1.2 GB". Default value is NO.
*/
@property BOOL zeroPadsFractionDigits;

/* Specify the formatting context for the formatted string. Default is NSFormattingContextUnknown.
*/
@property NSFormattingContext formattingContext NS_AVAILABLE(10_10, 8_0);

@end

NS_ASSUME_NONNULL_END

Data轉(zhuǎn)JSONString

+ (NSString *)prettyJSONStringFromData:(NSData *)data {
    NSString *prettyString = nil;

    id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
    if ([NSJSONSerialization isValidJSONObject:jsonObject]) {
        prettyString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:NULL] encoding:NSUTF8StringEncoding];
        // NSJSONSerialization escapes forward slashes. We want pretty json, so run through and unescape the slashes.
        prettyString = [prettyString stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
    } else {
        prettyString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }

    return prettyString;
}

判斷指定類的實例有沒有實現(xiàn)某方法

+ (BOOL)instanceRespondsButDoesNotImplementSelector:(SEL)selector class:(Class)cls {
    if ([cls instancesRespondToSelector:selector]) {
        unsigned int numMethods = 0;
        Method *methods = class_copyMethodList(cls, &numMethods);

        BOOL implementsSelector = NO;
        for (int index = 0; index < numMethods; index++) {
            SEL methodSelector = method_getName(methods[index]);
            if (selector == methodSelector) {
                implementsSelector = YES;
                break;
            }
        }

        free(methods);

        if (!implementsSelector) {
            return YES;
        }
    }

    return NO;
}

objc_msgSend

用該語句可以實現(xiàn)消息的發(fā)送秤涩,即便是那些系統(tǒng)禁止手動調(diào)用的方法陶舞,如-dealloc;

((void(*)(id, SEL))objc_msgSend)(self, NSSelectorFromString(@"dealloc"));

FLEXUtility 模塊

加載InfoPlist中配置的設(shè)備支持的方向值

+ (UIInterfaceOrientationMask)infoPlistSupportedInterfaceOrientationsMask {
    NSArray *supportedOrientations = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations"];
    UIInterfaceOrientationMask supportedOrientationsMask = 0;
    if ([supportedOrientations containsObject:@"UIInterfaceOrientationPortrait"]) {
        supportedOrientationsMask |= UIInterfaceOrientationMaskPortrait;
    }
    if ([supportedOrientations containsObject:@"UIInterfaceOrientationMaskLandscapeRight"]) {
        supportedOrientationsMask |= UIInterfaceOrientationMaskLandscapeRight;
    }
    if ([supportedOrientations containsObject:@"UIInterfaceOrientationMaskPortraitUpsideDown"]) {
        supportedOrientationsMask |= UIInterfaceOrientationMaskPortraitUpsideDown;
    }
    if ([supportedOrientations containsObject:@"UIInterfaceOrientationLandscapeLeft"]) {
        supportedOrientationsMask |= UIInterfaceOrientationMaskLandscapeLeft;
    }
    return supportedOrientationsMask;
}

生成縮略圖

/**
*  初始化并返回指定的數(shù)據(jù)圖像的縮略圖對象
*
*  @param data 包含圖像數(shù)據(jù)的數(shù)據(jù)對象
*  @param size 生成的縮略圖的最大寬高值
*
*  @return 返回一個初始化的UIImage對象,如果方法不能從指定的數(shù)據(jù)初始化圖像則返回空
*/
+ (UIImage *)amk_thumbnailedImageWithData:(NSData *)data maxPixelSize:(CGFloat)size {
    UIImage *thumbnail = nil;
    CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)data, 0);
    if (imageSource) {
        NSDictionary *options = @{ (__bridge id)kCGImageSourceCreateThumbnailWithTransform : @YES,
                                   (__bridge id)kCGImageSourceCreateThumbnailFromImageAlways : @YES,
                                   (__bridge id)kCGImageSourceThumbnailMaxPixelSize : @(size) };

        CGImageRef scaledImageRef = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, (__bridge CFDictionaryRef)options);
        if (scaledImageRef) {
            thumbnail = [UIImage imageWithCGImage:scaledImageRef];
            CFRelease(scaledImageRef);
        }
        CFRelease(imageSource);
    }
    return thumbnail;
}

URL Query解析為字典

+ (NSDictionary *)dictionaryFromQuery:(NSString *)query {
    NSMutableDictionary *queryDictionary = [NSMutableDictionary dictionary];

    // [a=1, b=2, c=3]
    NSArray *queryComponents = [query componentsSeparatedByString:@"&"];
    for (NSString *keyValueString in queryComponents) {
    // [a, 1]
    NSArray *components = [keyValueString componentsSeparatedByString:@"="];
    if ([components count] == 2) {
        NSString *key = [[components firstObject] stringByRemovingPercentEncoding];
        id value = [[components lastObject] stringByRemovingPercentEncoding];

        // Handle multiple entries under the same key as an array
        id existingEntry = queryDictionary[key];
        if (existingEntry) {
            if ([existingEntry isKindOfClass:[NSArray class]]) {
                value = [existingEntry arrayByAddingObject:value];
            } else {
                value = @[existingEntry, value];
            }
        }

        [queryDictionary setObject:value forKey:key];
        }
    }

    return queryDictionary;
}

JSONString

+ (NSString *)prettyJSONStringFromData:(NSData *)data {
    NSString *prettyString = nil;

    id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
    if ([NSJSONSerialization isValidJSONObject:jsonObject]) {
        prettyString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:NULL] encoding:NSUTF8StringEncoding];
        // NSJSONSerialization escapes forward slashes. We want pretty json, so run through and unescape the slashes.
        prettyString = [prettyString stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
    } else {
        prettyString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }

    return prettyString;
}

數(shù)據(jù)解壓

#import <zlib.h>

// Thanks to the following links for help with this method
// http://www.cocoanetics.com/2012/02/decompressing-files-into-memory/
// https://github.com/nicklockwood/GZIP
+ (NSData *)inflatedDataFromCompressedData:(NSData *)compressedData {
    NSData *inflatedData = nil;
    NSUInteger compressedDataLength = [compressedData length];
    if (compressedDataLength > 0) {
        z_stream stream;
        stream.zalloc = Z_NULL;
        stream.zfree = Z_NULL;
        stream.avail_in = (uInt)compressedDataLength;
        stream.next_in = (void *)[compressedData bytes];
        stream.total_out = 0;
        stream.avail_out = 0;

        NSMutableData *mutableData = [NSMutableData dataWithLength:compressedDataLength * 1.5];
        if (inflateInit2(&stream, 15 + 32) == Z_OK) {
        int status = Z_OK;
        while (status == Z_OK) {
            if (stream.total_out >= [mutableData length]) {
                mutableData.length += compressedDataLength / 2;
            }
            stream.next_out = (uint8_t *)[mutableData mutableBytes] + stream.total_out;
            stream.avail_out = (uInt)([mutableData length] - stream.total_out);
            status = inflate(&stream, Z_SYNC_FLUSH);
            }
            if (inflateEnd(&stream) == Z_OK) {
                if (status == Z_STREAM_END) {
                    mutableData.length = stream.total_out;
                    inflatedData = [mutableData copy];
                }
            }
        }
    }
    return inflatedData;
}

AllWindows

+ (NSArray *)allWindows {
    BOOL includeInternalWindows = YES;
    BOOL onlyVisibleWindows = NO;

    NSArray *allWindowsComponents = @[@"al", @"lWindo", @"wsIncl", @"udingInt", @"ernalWin", @"dows:o", @"nlyVisi", @"bleWin", @"dows:"];
    SEL allWindowsSelector = NSSelectorFromString([allWindowsComponents componentsJoinedByString:@""]);

    NSMethodSignature *methodSignature = [[UIWindow class] methodSignatureForSelector:allWindowsSelector];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];

    invocation.target = [UIWindow class];
    invocation.selector = allWindowsSelector;
    [invocation setArgument:&includeInternalWindows atIndex:2];
    [invocation setArgument:&onlyVisibleWindows atIndex:3];
    [invocation invoke];

    __unsafe_unretained NSArray *windows = nil;
    [invocation getReturnValue:&windows];
    return windows;
}

判斷實例響應(yīng)并實現(xiàn)了指定方法

/**
*  判斷實例響應(yīng)并實現(xiàn)了指定方法
*
*  @author Andy__M, 2016/06/16 17:06
*  @param selector 方法名稱
*  @return 若實例響應(yīng)并實現(xiàn)了指定方法則返回YES撑帖,否則返回NO
*/
+ (BOOL)instanceRespondsButDoesNotImplementSelector:(SEL)selector class:(Class)cls {
    if ([cls instancesRespondToSelector:selector]) {
        unsigned int numMethods = 0;
        Method *methods = class_copyMethodList(cls, &numMethods);

        BOOL implementsSelector = NO;
        for (int index = 0; index < numMethods; index++) {
            SEL methodSelector = method_getName(methods[index]);
            if (selector == methodSelector) {
                implementsSelector = YES;
                break;
            }
        }

        free(methods);

        if (!implementsSelector) {
            return YES;
        }
    }

    return NO;
}

另類的拼串方式

#define FLEXEncodeClass(class) ("@\"" #class "\"")
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末蓉坎,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子胡嘿,更是在濱河造成了極大的恐慌蛉艾,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件衷敌,死亡現(xiàn)場離奇詭異勿侯,居然都是意外死亡,警方通過查閱死者的電腦和手機缴罗,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進店門助琐,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人面氓,你說我怎么就攤上這事兵钮」当ぃ” “怎么了?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵矢空,是天一觀的道長航罗。 經(jīng)常有香客問我,道長屁药,這世上最難降的妖魔是什么粥血? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮酿箭,結(jié)果婚禮上复亏,老公的妹妹穿的比我還像新娘。我一直安慰自己缭嫡,他們只是感情好缔御,可當(dāng)我...
    茶點故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著妇蛀,像睡著了一般耕突。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上评架,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天眷茁,我揣著相機與錄音,去河邊找鬼纵诞。 笑死上祈,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的浙芙。 我是一名探鬼主播登刺,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼嗡呼!你這毒婦竟也來了纸俭?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤晤锥,失蹤者是張志新(化名)和其女友劉穎掉蔬,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體矾瘾,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年箭启,在試婚紗的時候發(fā)現(xiàn)自己被綠了壕翩。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡傅寡,死狀恐怖放妈,靈堂內(nèi)的尸體忽然破棺而出北救,到底是詐尸還是另有隱情,我是刑警寧澤芜抒,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布珍策,位于F島的核電站,受9級特大地震影響宅倒,放射性物質(zhì)發(fā)生泄漏攘宙。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一拐迁、第九天 我趴在偏房一處隱蔽的房頂上張望蹭劈。 院中可真熱鬧,春花似錦线召、人聲如沸铺韧。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽哈打。三九已至,卻和暖如春讯壶,著一層夾襖步出監(jiān)牢的瞬間前酿,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工鹏溯, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留罢维,地道東北人。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓丙挽,卻偏偏與公主長得像肺孵,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子颜阐,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,724評論 2 354

推薦閱讀更多精彩內(nèi)容