text
stringlengths 9
39.2M
| dir
stringlengths 25
226
| lang
stringclasses 163
values | created_date
timestamp[s] | updated_date
timestamp[s] | repo_name
stringclasses 751
values | repo_full_name
stringclasses 752
values | star
int64 1.01k
183k
| len_tokens
int64 1
18.5M
|
|---|---|---|---|---|---|---|---|---|
```objective-c
//
// UIImage+MultiFormat.h
// SDWebImage
//
// Created by Olivier Poitrey on 07/06/13.
//
#import <UIKit/UIKit.h>
@interface UIImage (MultiFormat)
+ (UIImage *)sd_imageWithData:(NSData *)data;
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/UIImage+MultiFormat.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 60
|
```objective-c
//
// UIImage+GIF.m
// LBGIFImage
//
// Created by Laurin Brandner on 06.01.12.
//
#import "UIImage+GIF.h"
#import <ImageIO/ImageIO.h>
@implementation UIImage (GIF)
+ (UIImage *)sd_animatedGIFWithData:(NSData *)data {
if (!data) {
return nil;
}
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
size_t count = CGImageSourceGetCount(source);
UIImage *animatedImage;
if (count <= 1) {
animatedImage = [[UIImage alloc] initWithData:data];
}
else {
NSMutableArray *images = [NSMutableArray array];
NSTimeInterval duration = 0.0f;
for (size_t i = 0; i < count; i++) {
CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
duration += [self sd_frameDurationAtIndex:i source:source];
[images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
CGImageRelease(image);
}
if (!duration) {
duration = (1.0f / 10.0f) * count;
}
animatedImage = [UIImage animatedImageWithImages:images duration:duration];
}
CFRelease(source);
return animatedImage;
}
+ (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {
float frameDuration = 0.1f;
CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties;
NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary];
NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
if (delayTimeUnclampedProp) {
frameDuration = [delayTimeUnclampedProp floatValue];
}
else {
NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
if (delayTimeProp) {
frameDuration = [delayTimeProp floatValue];
}
}
// Many annoying ads specify a 0 duration to make an image flash as quickly as possible.
// We follow Firefox's behavior and use a duration of 100 ms for any frames that specify
// a duration of <= 10 ms. See <rdar://problem/7689300> and <path_to_url
// for more information.
if (frameDuration < 0.011f) {
frameDuration = 0.100f;
}
CFRelease(cfFrameProperties);
return frameDuration;
}
+ (UIImage *)sd_animatedGIFNamed:(NSString *)name {
CGFloat scale = [UIScreen mainScreen].scale;
if (scale > 1.0f) {
NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"];
NSData *data = [NSData dataWithContentsOfFile:retinaPath];
if (data) {
return [UIImage sd_animatedGIFWithData:data];
}
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
data = [NSData dataWithContentsOfFile:path];
if (data) {
return [UIImage sd_animatedGIFWithData:data];
}
return [UIImage imageNamed:name];
}
else {
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
NSData *data = [NSData dataWithContentsOfFile:path];
if (data) {
return [UIImage sd_animatedGIFWithData:data];
}
return [UIImage imageNamed:name];
}
}
- (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size {
if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) {
return self;
}
CGSize scaledSize = size;
CGPoint thumbnailPoint = CGPointZero;
CGFloat widthFactor = size.width / self.size.width;
CGFloat heightFactor = size.height / self.size.height;
CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor : heightFactor;
scaledSize.width = self.size.width * scaleFactor;
scaledSize.height = self.size.height * scaleFactor;
if (widthFactor > heightFactor) {
thumbnailPoint.y = (size.height - scaledSize.height) * 0.5;
}
else if (widthFactor < heightFactor) {
thumbnailPoint.x = (size.width - scaledSize.width) * 0.5;
}
NSMutableArray *scaledImages = [NSMutableArray array];
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
for (UIImage *image in self.images) {
[image drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
[scaledImages addObject:newImage];
}
UIGraphicsEndImageContext();
return [UIImage animatedImageWithImages:scaledImages duration:self.duration];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/UIImage+GIF.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,108
|
```objective-c
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
#import "SDWebImageManager.h"
/**
* Integrates SDWebImage async downloading and caching of remote images with UIImageView.
*
* Usage with a UITableViewCell sub-class:
*
* @code
#import <SDWebImage/UIImageView+WebCache.h>
...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = @"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier]
autorelease];
}
// Here we use the provided sd_setImageWithURL: method to load the web image
// Ensure you use a placeholder image otherwise cells will be initialized with no image
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"path_to_url"]
placeholderImage:[UIImage imageNamed:@"placeholder"]];
cell.textLabel.text = @"My Text";
return cell;
}
* @endcode
*/
@interface UIImageView (WebCache)
/**
* Get the current image URL.
*
* Note that because of the limitations of categories this property can get out of sync
* if you use sd_setImage: directly.
*/
- (NSURL *)sd_imageURL;
/**
* Set the imageView `image` with an `url`.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
*/
- (void)sd_setImageWithURL:(NSURL *)url;
/**
* Set the imageView `image` with an `url` and a placeholder.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param placeholder The image to be set initially, until the image request finishes.
* @see sd_setImageWithURL:placeholderImage:options:
*/
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder;
/**
* Set the imageView `image` with an `url`, placeholder and custom options.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param placeholder The image to be set initially, until the image request finishes.
* @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
*/
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;
/**
* Set the imageView `image` with an `url`.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the image parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the image was retrived from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock;
/**
* Set the imageView `image` with an `url`, placeholder.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param placeholder The image to be set initially, until the image request finishes.
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the image parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the image was retrived from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;
/**
* Set the imageView `image` with an `url`, placeholder and custom options.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param placeholder The image to be set initially, until the image request finishes.
* @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the image parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the image was retrived from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
/**
* Set the imageView `image` with an `url`, placeholder and custom options.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param placeholder The image to be set initially, until the image request finishes.
* @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
* @param progressBlock A block called while image is downloading
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the image parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the image was retrived from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;
/**
* Set the imageView `image` with an `url` and a optionaly placeholder image.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param placeholder The image to be set initially, until the image request finishes.
* @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
* @param progressBlock A block called while image is downloading
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the image parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the image was retrived from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;
/**
* Download an array of images and starts them in an animation loop
*
* @param arrayOfURLs An array of NSURL
*/
- (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs;
/**
* Cancel the current download
*/
- (void)sd_cancelCurrentImageLoad;
- (void)sd_cancelCurrentAnimationImagesLoad;
@end
@interface UIImageView (WebCacheDeprecated)
- (NSURL *)imageURL __deprecated_msg("Use `sd_imageURL`");
- (void)setImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:`");
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:`");
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options`");
- (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:completed:`");
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:completed:`");
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:completed:`");
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:progress:completed:`");
- (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs __deprecated_msg("Use `sd_setAnimationImagesWithURLs:`");
- (void)cancelCurrentArrayLoad __deprecated_msg("Use `sd_cancelCurrentAnimationImagesLoad`");
- (void)cancelCurrentImageLoad __deprecated_msg("Use `sd_cancelCurrentImageLoad`");
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/UIImageView+WebCache.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 2,053
|
```objective-c
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* Created by james <path_to_url on 9/28/11.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
@interface UIImage (ForceDecode)
+ (UIImage *)decodedImageWithImage:(UIImage *)image;
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/SDWebImageDecoder.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 108
|
```objective-c
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageDownloader.h"
#import "SDWebImageDownloaderOperation.h"
#import <ImageIO/ImageIO.h>
NSString *const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification";
NSString *const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification";
static NSString *const kProgressCallbackKey = @"progress";
static NSString *const kCompletedCallbackKey = @"completed";
@interface SDWebImageDownloader ()
@property (strong, nonatomic) NSOperationQueue *downloadQueue;
@property (weak, nonatomic) NSOperation *lastAddedOperation;
@property (assign, nonatomic) Class operationClass;
@property (strong, nonatomic) NSMutableDictionary *URLCallbacks;
@property (strong, nonatomic) NSMutableDictionary *HTTPHeaders;
// This queue is used to serialize the handling of the network responses of all the download operation in a single queue
@property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t barrierQueue;
@end
@implementation SDWebImageDownloader
+ (void)initialize {
// Bind SDNetworkActivityIndicator if available (download it here: path_to_url )
// To use it, just add #import "SDNetworkActivityIndicator.h" in addition to the SDWebImage import
if (NSClassFromString(@"SDNetworkActivityIndicator")) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")];
#pragma clang diagnostic pop
// Remove observer in case it was previously added.
[[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStartNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStopNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:activityIndicator
selector:NSSelectorFromString(@"startActivity")
name:SDWebImageDownloadStartNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:activityIndicator
selector:NSSelectorFromString(@"stopActivity")
name:SDWebImageDownloadStopNotification object:nil];
}
}
+ (SDWebImageDownloader *)sharedDownloader {
static dispatch_once_t once;
static id instance;
dispatch_once(&once, ^{
instance = [self new];
});
return instance;
}
- (id)init {
if ((self = [super init])) {
_operationClass = [SDWebImageDownloaderOperation class];
_shouldDecompressImages = YES;
_executionOrder = SDWebImageDownloaderFIFOExecutionOrder;
_downloadQueue = [NSOperationQueue new];
_downloadQueue.maxConcurrentOperationCount = 6;
_URLCallbacks = [NSMutableDictionary new];
_HTTPHeaders = [NSMutableDictionary dictionaryWithObject:@"image/webp,image/*;q=0.8" forKey:@"Accept"];
_barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT);
_downloadTimeout = 15.0;
}
return self;
}
- (void)dealloc {
[self.downloadQueue cancelAllOperations];
SDDispatchQueueRelease(_barrierQueue);
}
- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field {
if (value) {
self.HTTPHeaders[field] = value;
}
else {
[self.HTTPHeaders removeObjectForKey:field];
}
}
- (NSString *)valueForHTTPHeaderField:(NSString *)field {
return self.HTTPHeaders[field];
}
- (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads {
_downloadQueue.maxConcurrentOperationCount = maxConcurrentDownloads;
}
- (NSUInteger)currentDownloadCount {
return _downloadQueue.operationCount;
}
- (NSInteger)maxConcurrentDownloads {
return _downloadQueue.maxConcurrentOperationCount;
}
- (void)setOperationClass:(Class)operationClass {
_operationClass = operationClass ?: [SDWebImageDownloaderOperation class];
}
- (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock {
__block SDWebImageDownloaderOperation *operation;
__weak SDWebImageDownloader *wself = self;
[self addProgressCallback:progressBlock andCompletedBlock:completedBlock forURL:url createCallback:^{
NSTimeInterval timeoutInterval = wself.downloadTimeout;
if (timeoutInterval == 0.0) {
timeoutInterval = 15.0;
}
// In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval];
request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies);
request.HTTPShouldUsePipelining = YES;
if (wself.headersFilter) {
request.allHTTPHeaderFields = wself.headersFilter(url, [wself.HTTPHeaders copy]);
}
else {
request.allHTTPHeaderFields = wself.HTTPHeaders;
}
operation = [[wself.operationClass alloc] initWithRequest:request
options:options
progress:^(NSInteger receivedSize, NSInteger expectedSize) {
SDWebImageDownloader *sself = wself;
if (!sself) return;
__block NSArray *callbacksForURL;
dispatch_sync(sself.barrierQueue, ^{
callbacksForURL = [sself.URLCallbacks[url] copy];
});
for (NSDictionary *callbacks in callbacksForURL) {
SDWebImageDownloaderProgressBlock callback = callbacks[kProgressCallbackKey];
if (callback) callback(receivedSize, expectedSize);
}
}
completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
SDWebImageDownloader *sself = wself;
if (!sself) return;
__block NSArray *callbacksForURL;
dispatch_barrier_sync(sself.barrierQueue, ^{
callbacksForURL = [sself.URLCallbacks[url] copy];
if (finished) {
[sself.URLCallbacks removeObjectForKey:url];
}
});
for (NSDictionary *callbacks in callbacksForURL) {
SDWebImageDownloaderCompletedBlock callback = callbacks[kCompletedCallbackKey];
if (callback) callback(image, data, error, finished);
}
}
cancelled:^{
SDWebImageDownloader *sself = wself;
if (!sself) return;
dispatch_barrier_async(sself.barrierQueue, ^{
[sself.URLCallbacks removeObjectForKey:url];
});
}];
operation.shouldDecompressImages = wself.shouldDecompressImages;
if (wself.username && wself.password) {
operation.credential = [NSURLCredential credentialWithUser:wself.username password:wself.password persistence:NSURLCredentialPersistenceForSession];
}
if (options & SDWebImageDownloaderHighPriority) {
operation.queuePriority = NSOperationQueuePriorityHigh;
} else if (options & SDWebImageDownloaderLowPriority) {
operation.queuePriority = NSOperationQueuePriorityLow;
}
[wself.downloadQueue addOperation:operation];
if (wself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) {
// Emulate LIFO execution order by systematically adding new operations as last operation's dependency
[wself.lastAddedOperation addDependency:operation];
wself.lastAddedOperation = operation;
}
}];
return operation;
}
- (void)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock andCompletedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock forURL:(NSURL *)url createCallback:(SDWebImageNoParamsBlock)createCallback {
// The URL will be used as the key to the callbacks dictionary so it cannot be nil. If it is nil immediately call the completed block with no image or data.
if (url == nil) {
if (completedBlock != nil) {
completedBlock(nil, nil, nil, NO);
}
return;
}
dispatch_barrier_sync(self.barrierQueue, ^{
BOOL first = NO;
if (!self.URLCallbacks[url]) {
self.URLCallbacks[url] = [NSMutableArray new];
first = YES;
}
// Handle single download of simultaneous download request for the same URL
NSMutableArray *callbacksForURL = self.URLCallbacks[url];
NSMutableDictionary *callbacks = [NSMutableDictionary new];
if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy];
if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy];
[callbacksForURL addObject:callbacks];
self.URLCallbacks[url] = callbacksForURL;
if (first) {
createCallback();
}
});
}
- (void)setSuspended:(BOOL)suspended {
[self.downloadQueue setSuspended:suspended];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/SDWebImageDownloader.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,958
|
```objective-c
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImagePrefetcher.h"
#if (!defined(DEBUG) && !defined (SD_VERBOSE)) || defined(SD_LOG_NONE)
#define NSLog(...)
#endif
@interface SDWebImagePrefetcher ()
@property (strong, nonatomic) SDWebImageManager *manager;
@property (strong, nonatomic) NSArray *prefetchURLs;
@property (assign, nonatomic) NSUInteger requestedCount;
@property (assign, nonatomic) NSUInteger skippedCount;
@property (assign, nonatomic) NSUInteger finishedCount;
@property (assign, nonatomic) NSTimeInterval startedTime;
@property (copy, nonatomic) SDWebImagePrefetcherCompletionBlock completionBlock;
@property (copy, nonatomic) SDWebImagePrefetcherProgressBlock progressBlock;
@end
@implementation SDWebImagePrefetcher
+ (SDWebImagePrefetcher *)sharedImagePrefetcher {
static dispatch_once_t once;
static id instance;
dispatch_once(&once, ^{
instance = [self new];
});
return instance;
}
- (id)init {
if ((self = [super init])) {
_manager = [SDWebImageManager new];
_options = SDWebImageLowPriority;
_prefetcherQueue = dispatch_get_main_queue();
self.maxConcurrentDownloads = 3;
}
return self;
}
- (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads {
self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads;
}
- (NSUInteger)maxConcurrentDownloads {
return self.manager.imageDownloader.maxConcurrentDownloads;
}
- (void)startPrefetchingAtIndex:(NSUInteger)index {
if (index >= self.prefetchURLs.count) return;
self.requestedCount++;
[self.manager downloadImageWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (!finished) return;
self.finishedCount++;
if (image) {
if (self.progressBlock) {
self.progressBlock(self.finishedCount,[self.prefetchURLs count]);
}
NSLog(@"Prefetched %@ out of %@", @(self.finishedCount), @(self.prefetchURLs.count));
}
else {
if (self.progressBlock) {
self.progressBlock(self.finishedCount,[self.prefetchURLs count]);
}
NSLog(@"Prefetched %@ out of %@ (Failed)", @(self.finishedCount), @(self.prefetchURLs.count));
// Add last failed
self.skippedCount++;
}
if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) {
[self.delegate imagePrefetcher:self
didPrefetchURL:self.prefetchURLs[index]
finishedCount:self.finishedCount
totalCount:self.prefetchURLs.count
];
}
if (self.prefetchURLs.count > self.requestedCount) {
dispatch_async(self.prefetcherQueue, ^{
[self startPrefetchingAtIndex:self.requestedCount];
});
}
else if (self.finishedCount == self.requestedCount) {
[self reportStatus];
if (self.completionBlock) {
self.completionBlock(self.finishedCount, self.skippedCount);
self.completionBlock = nil;
}
}
}];
}
- (void)reportStatus {
NSUInteger total = [self.prefetchURLs count];
NSLog(@"Finished prefetching (%@ successful, %@ skipped, timeElasped %.2f)", @(total - self.skippedCount), @(self.skippedCount), CFAbsoluteTimeGetCurrent() - self.startedTime);
if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) {
[self.delegate imagePrefetcher:self
didFinishWithTotalCount:(total - self.skippedCount)
skippedCount:self.skippedCount
];
}
}
- (void)prefetchURLs:(NSArray *)urls {
[self prefetchURLs:urls progress:nil completed:nil];
}
- (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock {
[self cancelPrefetching]; // Prevent duplicate prefetch request
self.startedTime = CFAbsoluteTimeGetCurrent();
self.prefetchURLs = urls;
self.completionBlock = completionBlock;
self.progressBlock = progressBlock;
if(urls.count == 0){
if(completionBlock){
completionBlock(0,0);
}
}else{
// Starts prefetching from the very first image on the list with the max allowed concurrency
NSUInteger listCount = self.prefetchURLs.count;
for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) {
[self startPrefetchingAtIndex:i];
}
}
}
- (void)cancelPrefetching {
self.prefetchURLs = nil;
self.skippedCount = 0;
self.requestedCount = 0;
self.finishedCount = 0;
[self.manager cancelAll];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/SDWebImagePrefetcher.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,152
|
```objective-c
//
// SDWebImageCompat.m
// SDWebImage
//
// Created by Olivier Poitrey on 11/12/12.
//
#import "SDWebImageCompat.h"
#if !__has_feature(objc_arc)
#error SDWebImage is ARC only. Either turn on ARC for the project or use -fobjc-arc flag
#endif
inline UIImage *SDScaledImageForKey(NSString *key, UIImage *image) {
if (!image) {
return nil;
}
if ([image.images count] > 0) {
NSMutableArray *scaledImages = [NSMutableArray array];
for (UIImage *tempImage in image.images) {
[scaledImages addObject:SDScaledImageForKey(key, tempImage)];
}
return [UIImage animatedImageWithImages:scaledImages duration:image.duration];
}
else {
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
CGFloat scale = 1.0;
if (key.length >= 8) {
// Search @2x. at the end of the string, before a 3 to 4 extension length (only if key len is 8 or more @2x. + 4 len ext)
NSRange range = [key rangeOfString:@"@2x." options:0 range:NSMakeRange(key.length - 8, 5)];
if (range.location != NSNotFound) {
scale = 2.0;
}
}
UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation];
image = scaledImage;
}
return image;
}
}
```
|
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/SDWebImageCompat.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 340
|
```objective-c
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageManager.h"
#import <objc/message.h>
@interface SDWebImageCombinedOperation : NSObject <SDWebImageOperation>
@property (assign, nonatomic, getter = isCancelled) BOOL cancelled;
@property (copy, nonatomic) SDWebImageNoParamsBlock cancelBlock;
@property (strong, nonatomic) NSOperation *cacheOperation;
@end
@interface SDWebImageManager ()
@property (strong, nonatomic, readwrite) SDImageCache *imageCache;
@property (strong, nonatomic, readwrite) SDWebImageDownloader *imageDownloader;
@property (strong, nonatomic) NSMutableArray *failedURLs;
@property (strong, nonatomic) NSMutableArray *runningOperations;
@end
@implementation SDWebImageManager
+ (id)sharedManager {
static dispatch_once_t once;
static id instance;
dispatch_once(&once, ^{
instance = [self new];
});
return instance;
}
- (id)init {
if ((self = [super init])) {
_imageCache = [self createCache];
_imageDownloader = [SDWebImageDownloader sharedDownloader];
_failedURLs = [NSMutableArray new];
_runningOperations = [NSMutableArray new];
}
return self;
}
- (SDImageCache *)createCache {
return [SDImageCache sharedImageCache];
}
- (NSString *)cacheKeyForURL:(NSURL *)url {
if (self.cacheKeyFilter) {
return self.cacheKeyFilter(url);
}
else {
return [url absoluteString];
}
}
- (BOOL)cachedImageExistsForURL:(NSURL *)url {
NSString *key = [self cacheKeyForURL:url];
if ([self.imageCache imageFromMemoryCacheForKey:key] != nil) return YES;
return [self.imageCache diskImageExistsWithKey:key];
}
- (BOOL)diskImageExistsForURL:(NSURL *)url {
NSString *key = [self cacheKeyForURL:url];
return [self.imageCache diskImageExistsWithKey:key];
}
- (void)cachedImageExistsForURL:(NSURL *)url
completion:(SDWebImageCheckCacheCompletionBlock)completionBlock {
NSString *key = [self cacheKeyForURL:url];
BOOL isInMemoryCache = ([self.imageCache imageFromMemoryCacheForKey:key] != nil);
if (isInMemoryCache) {
// making sure we call the completion block on the main queue
dispatch_async(dispatch_get_main_queue(), ^{
if (completionBlock) {
completionBlock(YES);
}
});
return;
}
[self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) {
// the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
if (completionBlock) {
completionBlock(isInDiskCache);
}
}];
}
- (void)diskImageExistsForURL:(NSURL *)url
completion:(SDWebImageCheckCacheCompletionBlock)completionBlock {
NSString *key = [self cacheKeyForURL:url];
[self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) {
// the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
if (completionBlock) {
completionBlock(isInDiskCache);
}
}];
}
- (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url
options:(SDWebImageOptions)options
progress:(SDWebImageDownloaderProgressBlock)progressBlock
completed:(SDWebImageCompletionWithFinishedBlock)completedBlock {
// Invoking this method without a completedBlock is pointless
NSAssert(completedBlock != nil, @"If you mean to prefetch the image, use -[SDWebImagePrefetcher prefetchURLs] instead");
// Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, XCode won't
// throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString.
if ([url isKindOfClass:NSString.class]) {
url = [NSURL URLWithString:(NSString *)url];
}
// Prevents app crashing on argument type error like sending NSNull instead of NSURL
if (![url isKindOfClass:NSURL.class]) {
url = nil;
}
__block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new];
__weak SDWebImageCombinedOperation *weakOperation = operation;
BOOL isFailedUrl = NO;
@synchronized (self.failedURLs) {
isFailedUrl = [self.failedURLs containsObject:url];
}
if (!url || (!(options & SDWebImageRetryFailed) && isFailedUrl)) {
dispatch_main_sync_safe(^{
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil];
completedBlock(nil, error, SDImageCacheTypeNone, YES, url);
});
return operation;
}
@synchronized (self.runningOperations) {
[self.runningOperations addObject:operation];
}
NSString *key = [self cacheKeyForURL:url];
operation.cacheOperation = [self.imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType) {
if (operation.isCancelled) {
@synchronized (self.runningOperations) {
[self.runningOperations removeObject:operation];
}
return;
}
if ((!image || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) {
if (image && options & SDWebImageRefreshCached) {
dispatch_main_sync_safe(^{
// If image was found in the cache bug SDWebImageRefreshCached is provided, notify about the cached image
// AND try to re-download it in order to let a chance to NSURLCache to refresh it from server.
completedBlock(image, nil, cacheType, YES, url);
});
}
// download if no image or requested to refresh anyway, and download allowed by delegate
SDWebImageDownloaderOptions downloaderOptions = 0;
if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority;
if (options & SDWebImageProgressiveDownload) downloaderOptions |= SDWebImageDownloaderProgressiveDownload;
if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache;
if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground;
if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies;
if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates;
if (options & SDWebImageHighPriority) downloaderOptions |= SDWebImageDownloaderHighPriority;
if (image && options & SDWebImageRefreshCached) {
// force progressive off if image already cached but forced refreshing
downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload;
// ignore image read from NSURLCache if image if cached but force refreshing
downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse;
}
id <SDWebImageOperation> subOperation = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *data, NSError *error, BOOL finished) {
if (weakOperation.isCancelled) {
// Do nothing if the operation was cancelled
// See #699 for more details
// if we would call the completedBlock, there could be a race condition between this block and another completedBlock for the same object, so if this one is called second, we will overwrite the new data
}
else if (error) {
dispatch_main_sync_safe(^{
if (!weakOperation.isCancelled) {
completedBlock(nil, error, SDImageCacheTypeNone, finished, url);
}
});
if (error.code != NSURLErrorNotConnectedToInternet && error.code != NSURLErrorCancelled && error.code != NSURLErrorTimedOut) {
@synchronized (self.failedURLs) {
if (![self.failedURLs containsObject:url]) {
[self.failedURLs addObject:url];
}
}
}
}
else {
BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly);
if (options & SDWebImageRefreshCached && image && !downloadedImage) {
// Image refresh hit the NSURLCache cache, do not call the completion block
}
else if (downloadedImage && (!downloadedImage.images || (options & SDWebImageTransformAnimatedImage)) && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url];
if (transformedImage && finished) {
BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage];
[self.imageCache storeImage:transformedImage recalculateFromImage:imageWasTransformed imageData:data forKey:key toDisk:cacheOnDisk];
}
dispatch_main_sync_safe(^{
if (!weakOperation.isCancelled) {
completedBlock(transformedImage, nil, SDImageCacheTypeNone, finished, url);
}
});
});
}
else {
if (downloadedImage && finished) {
[self.imageCache storeImage:downloadedImage recalculateFromImage:NO imageData:data forKey:key toDisk:cacheOnDisk];
}
dispatch_main_sync_safe(^{
if (!weakOperation.isCancelled) {
completedBlock(downloadedImage, nil, SDImageCacheTypeNone, finished, url);
}
});
}
}
if (finished) {
@synchronized (self.runningOperations) {
[self.runningOperations removeObject:operation];
}
}
}];
operation.cancelBlock = ^{
[subOperation cancel];
@synchronized (self.runningOperations) {
[self.runningOperations removeObject:weakOperation];
}
};
}
else if (image) {
dispatch_main_sync_safe(^{
if (!weakOperation.isCancelled) {
completedBlock(image, nil, cacheType, YES, url);
}
});
@synchronized (self.runningOperations) {
[self.runningOperations removeObject:operation];
}
}
else {
// Image not in cache and download disallowed by delegate
dispatch_main_sync_safe(^{
if (!weakOperation.isCancelled) {
completedBlock(nil, nil, SDImageCacheTypeNone, YES, url);
}
});
@synchronized (self.runningOperations) {
[self.runningOperations removeObject:operation];
}
}
}];
return operation;
}
- (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url {
if (image && url) {
NSString *key = [self cacheKeyForURL:url];
[self.imageCache storeImage:image forKey:key toDisk:YES];
}
}
- (void)cancelAll {
@synchronized (self.runningOperations) {
NSArray *copiedOperations = [self.runningOperations copy];
[copiedOperations makeObjectsPerformSelector:@selector(cancel)];
[self.runningOperations removeObjectsInArray:copiedOperations];
}
}
- (BOOL)isRunning {
return self.runningOperations.count > 0;
}
@end
@implementation SDWebImageCombinedOperation
- (void)setCancelBlock:(SDWebImageNoParamsBlock)cancelBlock {
// check if the operation is already cancelled, then we just call the cancelBlock
if (self.isCancelled) {
if (cancelBlock) {
cancelBlock();
}
_cancelBlock = nil; // don't forget to nil the cancelBlock, otherwise we will get crashes
} else {
_cancelBlock = [cancelBlock copy];
}
}
- (void)cancel {
self.cancelled = YES;
if (self.cacheOperation) {
[self.cacheOperation cancel];
self.cacheOperation = nil;
}
if (self.cancelBlock) {
self.cancelBlock();
// TODO: this is a temporary fix to #809.
// Until we can figure the exact cause of the crash, going with the ivar instead of the setter
// self.cancelBlock = nil;
_cancelBlock = nil;
}
}
@end
@implementation SDWebImageManager (Deprecated)
// deprecated method, uses the non deprecated method
// adapter for the completion block
- (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedWithFinishedBlock)completedBlock {
return [self downloadImageWithURL:url
options:options
progress:progressBlock
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (completedBlock) {
completedBlock(image, error, cacheType, finished);
}
}];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/SDWebImageManager.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 2,865
|
```objective-c
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "UIImageView+WebCache.h"
#import "objc/runtime.h"
#import "UIView+WebCacheOperation.h"
static char imageURLKey;
@implementation UIImageView (WebCache)
- (void)sd_setImageWithURL:(NSURL *)url {
[self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil];
}
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder {
[self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil];
}
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
[self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil];
}
- (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock {
[self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock];
}
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock {
[self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock];
}
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {
[self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock];
}
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
[self sd_cancelCurrentImageLoad];
objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if (!(options & SDWebImageDelayPlaceholder)) {
dispatch_main_async_safe(^{
self.image = placeholder;
});
}
if (url) {
__weak UIImageView *wself = self;
id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (!wself) return;
dispatch_main_sync_safe(^{
if (!wself) return;
if (image) {
wself.image = image;
[wself setNeedsLayout];
} else {
if ((options & SDWebImageDelayPlaceholder)) {
wself.image = placeholder;
[wself setNeedsLayout];
}
}
if (completedBlock && finished) {
completedBlock(image, error, cacheType, url);
}
});
}];
[self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"];
} else {
dispatch_main_async_safe(^{
NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
if (completedBlock) {
completedBlock(nil, error, SDImageCacheTypeNone, url);
}
});
}
}
- (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:url];
UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key];
[self sd_setImageWithURL:url placeholderImage:lastPreviousCachedImage ?: placeholder options:options progress:progressBlock completed:completedBlock];
}
- (NSURL *)sd_imageURL {
return objc_getAssociatedObject(self, &imageURLKey);
}
- (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs {
[self sd_cancelCurrentAnimationImagesLoad];
__weak UIImageView *wself = self;
NSMutableArray *operationsArray = [[NSMutableArray alloc] init];
for (NSURL *logoImageURL in arrayOfURLs) {
id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (!wself) return;
dispatch_main_sync_safe(^{
__strong UIImageView *sself = wself;
[sself stopAnimating];
if (sself && image) {
NSMutableArray *currentImages = [[sself animationImages] mutableCopy];
if (!currentImages) {
currentImages = [[NSMutableArray alloc] init];
}
[currentImages addObject:image];
sself.animationImages = currentImages;
[sself setNeedsLayout];
}
[sself startAnimating];
});
}];
[operationsArray addObject:operation];
}
[self sd_setImageLoadOperation:[NSArray arrayWithArray:operationsArray] forKey:@"UIImageViewAnimationImages"];
}
- (void)sd_cancelCurrentImageLoad {
[self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"];
}
- (void)sd_cancelCurrentAnimationImagesLoad {
[self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"];
}
@end
@implementation UIImageView (WebCacheDeprecated)
- (NSURL *)imageURL {
return [self sd_imageURL];
}
- (void)setImageWithURL:(NSURL *)url {
[self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil];
}
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder {
[self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil];
}
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
[self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil];
}
- (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock {
[self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (completedBlock) {
completedBlock(image, error, cacheType);
}
}];
}
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock {
[self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (completedBlock) {
completedBlock(image, error, cacheType);
}
}];
}
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock {
[self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (completedBlock) {
completedBlock(image, error, cacheType);
}
}];
}
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock {
[self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (completedBlock) {
completedBlock(image, error, cacheType);
}
}];
}
- (void)cancelCurrentArrayLoad {
[self sd_cancelCurrentAnimationImagesLoad];
}
- (void)cancelCurrentImageLoad {
[self sd_cancelCurrentImageLoad];
}
- (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs {
[self sd_setAnimationImagesWithURLs:arrayOfURLs];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/UIImageView+WebCache.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,805
|
```objective-c
//
// UIImage+MultiFormat.m
// SDWebImage
//
// Created by Olivier Poitrey on 07/06/13.
//
#import "UIImage+MultiFormat.h"
#import "UIImage+GIF.h"
#import "NSData+ImageContentType.h"
#import <ImageIO/ImageIO.h>
#ifdef SD_WEBP
#import "UIImage+WebP.h"
#endif
@implementation UIImage (MultiFormat)
+ (UIImage *)sd_imageWithData:(NSData *)data {
UIImage *image;
NSString *imageContentType = [NSData sd_contentTypeForImageData:data];
if ([imageContentType isEqualToString:@"image/gif"]) {
image = [UIImage sd_animatedGIFWithData:data];
}
#ifdef SD_WEBP
else if ([imageContentType isEqualToString:@"image/webp"])
{
image = [UIImage imageWithWebPData:data];
}
#endif
else {
image = [[UIImage alloc] initWithData:data];
UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data];
if (orientation != UIImageOrientationUp) {
image = [UIImage imageWithCGImage:image.CGImage
scale:image.scale
orientation:orientation];
}
}
return image;
}
+(UIImageOrientation)sd_imageOrientationFromImageData:(NSData *)imageData {
UIImageOrientation result = UIImageOrientationUp;
CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL);
if (imageSource) {
CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL);
if (properties) {
CFTypeRef val;
int exifOrientation;
val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation);
if (val) {
CFNumberGetValue(val, kCFNumberIntType, &exifOrientation);
result = [self sd_exifOrientationToiOSOrientation:exifOrientation];
} // else - if it's not set it remains at up
CFRelease((CFTypeRef) properties);
} else {
//NSLog(@"NO PROPERTIES, FAIL");
}
CFRelease(imageSource);
}
return result;
}
#pragma mark EXIF orientation tag converter
// Convert an EXIF image orientation to an iOS one.
// reference see here: path_to_url
+ (UIImageOrientation) sd_exifOrientationToiOSOrientation:(int)exifOrientation {
UIImageOrientation orientation = UIImageOrientationUp;
switch (exifOrientation) {
case 1:
orientation = UIImageOrientationUp;
break;
case 3:
orientation = UIImageOrientationDown;
break;
case 8:
orientation = UIImageOrientationLeft;
break;
case 6:
orientation = UIImageOrientationRight;
break;
case 2:
orientation = UIImageOrientationUpMirrored;
break;
case 4:
orientation = UIImageOrientationDownMirrored;
break;
case 5:
orientation = UIImageOrientationLeftMirrored;
break;
case 7:
orientation = UIImageOrientationRightMirrored;
break;
default:
break;
}
return orientation;
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/UIImage+MultiFormat.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 660
|
```objective-c
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
#import "SDWebImageManager.h"
/**
* Integrates SDWebImage async downloading and caching of remote images with UIButtonView.
*/
@interface UIButton (WebCache)
/**
* Get the current image URL.
*/
- (NSURL *)sd_currentImageURL;
/**
* Get the image URL for a control state.
*
* @param state Which state you want to know the URL for. The values are described in UIControlState.
*/
- (NSURL *)sd_imageURLForState:(UIControlState)state;
/**
* Set the imageView `image` with an `url`.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param state The state that uses the specified title. The values are described in UIControlState.
*/
- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state;
/**
* Set the imageView `image` with an `url` and a placeholder.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param state The state that uses the specified title. The values are described in UIControlState.
* @param placeholder The image to be set initially, until the image request finishes.
* @see sd_setImageWithURL:placeholderImage:options:
*/
- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder;
/**
* Set the imageView `image` with an `url`, placeholder and custom options.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param state The state that uses the specified title. The values are described in UIControlState.
* @param placeholder The image to be set initially, until the image request finishes.
* @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
*/
- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;
/**
* Set the imageView `image` with an `url`.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param state The state that uses the specified title. The values are described in UIControlState.
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the image parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the image was retrived from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock;
/**
* Set the imageView `image` with an `url`, placeholder.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param state The state that uses the specified title. The values are described in UIControlState.
* @param placeholder The image to be set initially, until the image request finishes.
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the image parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the image was retrived from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;
/**
* Set the imageView `image` with an `url`, placeholder and custom options.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param state The state that uses the specified title. The values are described in UIControlState.
* @param placeholder The image to be set initially, until the image request finishes.
* @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the image parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the image was retrived from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
/**
* Set the backgroundImageView `image` with an `url`.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param state The state that uses the specified title. The values are described in UIControlState.
*/
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state;
/**
* Set the backgroundImageView `image` with an `url` and a placeholder.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param state The state that uses the specified title. The values are described in UIControlState.
* @param placeholder The image to be set initially, until the image request finishes.
* @see sd_setImageWithURL:placeholderImage:options:
*/
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder;
/**
* Set the backgroundImageView `image` with an `url`, placeholder and custom options.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param state The state that uses the specified title. The values are described in UIControlState.
* @param placeholder The image to be set initially, until the image request finishes.
* @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
*/
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;
/**
* Set the backgroundImageView `image` with an `url`.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param state The state that uses the specified title. The values are described in UIControlState.
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the image parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the image was retrived from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock;
/**
* Set the backgroundImageView `image` with an `url`, placeholder.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param state The state that uses the specified title. The values are described in UIControlState.
* @param placeholder The image to be set initially, until the image request finishes.
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the image parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the image was retrived from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;
/**
* Set the backgroundImageView `image` with an `url`, placeholder and custom options.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param placeholder The image to be set initially, until the image request finishes.
* @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the image parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the image was retrived from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
/**
* Cancel the current image download
*/
- (void)sd_cancelImageLoadForState:(UIControlState)state;
/**
* Cancel the current backgroundImage download
*/
- (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state;
@end
@interface UIButton (WebCacheDeprecated)
- (NSURL *)currentImageURL __deprecated_msg("Use `sd_currentImageURL`");
- (NSURL *)imageURLForState:(UIControlState)state __deprecated_msg("Use `sd_imageURLForState:`");
- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:`");
- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:`");
- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:options:`");
- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:completed:`");
- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:completed:`");
- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:options:completed:`");
- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:`");
- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:`");
- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:options:`");
- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:completed:`");
- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:completed:`");
- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:options:completed:`");
- (void)cancelCurrentImageLoad __deprecated_msg("Use `sd_cancelImageLoadForState:`");
- (void)cancelBackgroundImageLoadForState:(UIControlState)state __deprecated_msg("Use `sd_cancelBackgroundImageLoadForState:`");
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/UIButton+WebCache.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 2,819
|
```objective-c
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageDownloader.h"
#import "SDWebImageOperation.h"
@interface SDWebImageDownloaderOperation : NSOperation <SDWebImageOperation>
/**
* The request used by the operation's connection.
*/
@property (strong, nonatomic, readonly) NSURLRequest *request;
@property (assign, nonatomic) BOOL shouldDecompressImages;
/**
* Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default.
*
* This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`.
*/
@property (nonatomic, assign) BOOL shouldUseCredentialStorage;
/**
* The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`.
*
* This will be overridden by any shared credentials that exist for the username or password of the request URL, if present.
*/
@property (nonatomic, strong) NSURLCredential *credential;
/**
* The SDWebImageDownloaderOptions for the receiver.
*/
@property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options;
/**
* Initializes a `SDWebImageDownloaderOperation` object
*
* @see SDWebImageDownloaderOperation
*
* @param request the URL request
* @param options downloader options
* @param progressBlock the block executed when a new chunk of data arrives.
* @note the progress block is executed on a background queue
* @param completedBlock the block executed when the download is done.
* @note the completed block is executed on the main queue for success. If errors are found, there is a chance the block will be executed on a background queue
* @param cancelBlock the block executed if the download (operation) is cancelled
*
* @return the initialized instance
*/
- (id)initWithRequest:(NSURLRequest *)request
options:(SDWebImageDownloaderOptions)options
progress:(SDWebImageDownloaderProgressBlock)progressBlock
completed:(SDWebImageDownloaderCompletedBlock)completedBlock
cancelled:(SDWebImageNoParamsBlock)cancelBlock;
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/SDWebImageDownloaderOperation.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 496
|
```objective-c
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageCompat.h"
#import "SDWebImageOperation.h"
#import "SDWebImageDownloader.h"
#import "SDImageCache.h"
typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) {
/**
* By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying.
* This flag disable this blacklisting.
*/
SDWebImageRetryFailed = 1 << 0,
/**
* By default, image downloads are started during UI interactions, this flags disable this feature,
* leading to delayed download on UIScrollView deceleration for instance.
*/
SDWebImageLowPriority = 1 << 1,
/**
* This flag disables on-disk caching
*/
SDWebImageCacheMemoryOnly = 1 << 2,
/**
* This flag enables progressive download, the image is displayed progressively during download as a browser would do.
* By default, the image is only displayed once completely downloaded.
*/
SDWebImageProgressiveDownload = 1 << 3,
/**
* Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed.
* The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation.
* This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics.
* If a cached image is refreshed, the completion block is called once with the cached image and again with the final image.
*
* Use this flag only if you can't make your URLs static with embeded cache busting parameter.
*/
SDWebImageRefreshCached = 1 << 4,
/**
* In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for
* extra time in background to let the request finish. If the background task expires the operation will be cancelled.
*/
SDWebImageContinueInBackground = 1 << 5,
/**
* Handles cookies stored in NSHTTPCookieStore by setting
* NSMutableURLRequest.HTTPShouldHandleCookies = YES;
*/
SDWebImageHandleCookies = 1 << 6,
/**
* Enable to allow untrusted SSL ceriticates.
* Useful for testing purposes. Use with caution in production.
*/
SDWebImageAllowInvalidSSLCertificates = 1 << 7,
/**
* By default, image are loaded in the order they were queued. This flag move them to
* the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which
* could take a while).
*/
SDWebImageHighPriority = 1 << 8,
/**
* By default, placeholder images are loaded while the image is loading. This flag will delay the loading
* of the placeholder image until after the image has finished loading.
*/
SDWebImageDelayPlaceholder = 1 << 9,
/**
* We usually don't call transformDownloadedImage delegate method on animated images,
* as most transformation code would mangle it.
* Use this flag to transform them anyway.
*/
SDWebImageTransformAnimatedImage = 1 << 10,
};
typedef void(^SDWebImageCompletionBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL);
typedef void(^SDWebImageCompletionWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL);
typedef NSString *(^SDWebImageCacheKeyFilterBlock)(NSURL *url);
@class SDWebImageManager;
@protocol SDWebImageManagerDelegate <NSObject>
@optional
/**
* Controls which image should be downloaded when the image is not found in the cache.
*
* @param imageManager The current `SDWebImageManager`
* @param imageURL The url of the image to be downloaded
*
* @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied.
*/
- (BOOL)imageManager:(SDWebImageManager *)imageManager shouldDownloadImageForURL:(NSURL *)imageURL;
/**
* Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory.
* NOTE: This method is called from a global queue in order to not to block the main thread.
*
* @param imageManager The current `SDWebImageManager`
* @param image The image to transform
* @param imageURL The url of the image to transform
*
* @return The transformed image object.
*/
- (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL;
@end
/**
* The SDWebImageManager is the class behind the UIImageView+WebCache category and likes.
* It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache).
* You can use this class directly to benefit from web image downloading with caching in another context than
* a UIView.
*
* Here is a simple example of how to use SDWebImageManager:
*
* @code
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:imageURL
options:0
progress:nil
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (image) {
// do something with image
}
}];
* @endcode
*/
@interface SDWebImageManager : NSObject
@property (weak, nonatomic) id <SDWebImageManagerDelegate> delegate;
@property (strong, nonatomic, readonly) SDImageCache *imageCache;
@property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader;
/**
* The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can
* be used to remove dynamic part of an image URL.
*
* The following example sets a filter in the application delegate that will remove any query-string from the
* URL before to use it as a cache key:
*
* @code
[[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) {
url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path];
return [url absoluteString];
}];
* @endcode
*/
@property (nonatomic, copy) SDWebImageCacheKeyFilterBlock cacheKeyFilter;
/**
* Returns global SDWebImageManager instance.
*
* @return SDWebImageManager shared instance
*/
+ (SDWebImageManager *)sharedManager;
/**
* Downloads the image at the given URL if not present in cache or return the cached version otherwise.
*
* @param url The URL to the image
* @param options A mask to specify options to use for this request
* @param progressBlock A block called while image is downloading
* @param completedBlock A block called when operation has been completed.
*
* This parameter is required.
*
* This block has no return value and takes the requested UIImage as first parameter.
* In case of error the image parameter is nil and the second parameter may contain an NSError.
*
* The third parameter is an `SDImageCacheType` enum indicating if the image was retrived from the local cache
* or from the memory cache or from the network.
*
* The last parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is
* downloading. This block is thus called repetidly with a partial image. When image is fully downloaded, the
* block is called a last time with the full image and the last parameter set to YES.
*
* @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation
*/
- (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url
options:(SDWebImageOptions)options
progress:(SDWebImageDownloaderProgressBlock)progressBlock
completed:(SDWebImageCompletionWithFinishedBlock)completedBlock;
/**
* Saves image to cache for given URL
*
* @param image The image to cache
* @param url The URL to the image
*
*/
- (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url;
/**
* Cancel all current opreations
*/
- (void)cancelAll;
/**
* Check one or more operations running
*/
- (BOOL)isRunning;
/**
* Check if image has already been cached
*
* @param url image url
*
* @return if the image was already cached
*/
- (BOOL)cachedImageExistsForURL:(NSURL *)url;
/**
* Check if image has already been cached on disk only
*
* @param url image url
*
* @return if the image was already cached (disk only)
*/
- (BOOL)diskImageExistsForURL:(NSURL *)url;
/**
* Async check if image has already been cached
*
* @param url image url
* @param completionBlock the block to be executed when the check is finished
*
* @note the completion block is always executed on the main queue
*/
- (void)cachedImageExistsForURL:(NSURL *)url
completion:(SDWebImageCheckCacheCompletionBlock)completionBlock;
/**
* Async check if image has already been cached on disk only
*
* @param url image url
* @param completionBlock the block to be executed when the check is finished
*
* @note the completion block is always executed on the main queue
*/
- (void)diskImageExistsForURL:(NSURL *)url
completion:(SDWebImageCheckCacheCompletionBlock)completionBlock;
/**
*Return the cache key for a given URL
*/
- (NSString *)cacheKeyForURL:(NSURL *)url;
@end
#pragma mark - Deprecated
typedef void(^SDWebImageCompletedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionBlock`");
typedef void(^SDWebImageCompletedWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionWithFinishedBlock`");
@interface SDWebImageManager (Deprecated)
/**
* Downloads the image at the given URL if not present in cache or return the cached version otherwise.
*
* @deprecated This method has been deprecated. Use `downloadImageWithURL:options:progress:completed:`
*/
- (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url
options:(SDWebImageOptions)options
progress:(SDWebImageDownloaderProgressBlock)progressBlock
completed:(SDWebImageCompletedWithFinishedBlock)completedBlock __deprecated_msg("Method deprecated. Use `downloadImageWithURL:options:progress:completed:`");
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/SDWebImageManager.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 2,396
|
```objective-c
//
// UIImage+GIF.h
// LBGIFImage
//
// Created by Laurin Brandner on 06.01.12.
//
#import <UIKit/UIKit.h>
@interface UIImage (GIF)
+ (UIImage *)sd_animatedGIFNamed:(NSString *)name;
+ (UIImage *)sd_animatedGIFWithData:(NSData *)data;
- (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size;
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/UIImage+GIF.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 98
|
```objective-c
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <UIKit/UIKit.h>
#import "SDWebImageCompat.h"
#import "SDWebImageManager.h"
/**
* Integrates SDWebImage async downloading and caching of remote images with UIImageView for highlighted state.
*/
@interface UIImageView (HighlightedWebCache)
/**
* Set the imageView `highlightedImage` with an `url`.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
*/
- (void)sd_setHighlightedImageWithURL:(NSURL *)url;
/**
* Set the imageView `highlightedImage` with an `url` and custom options.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
*/
- (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options;
/**
* Set the imageView `highlightedImage` with an `url`.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the image parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the image was retrived from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock;
/**
* Set the imageView `highlightedImage` with an `url` and custom options.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the image parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the image was retrived from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
/**
* Set the imageView `highlightedImage` with an `url` and custom options.
*
* The download is asynchronous and cached.
*
* @param url The url for the image.
* @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
* @param progressBlock A block called while image is downloading
* @param completedBlock A block called when operation has been completed. This block has no return value
* and takes the requested UIImage as first parameter. In case of error the image parameter
* is nil and the second parameter may contain an NSError. The third parameter is a Boolean
* indicating if the image was retrived from the local cache or from the network.
* The fourth parameter is the original image url.
*/
- (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;
/**
* Cancel the current download
*/
- (void)sd_cancelCurrentHighlightedImageLoad;
@end
@interface UIImageView (HighlightedWebCacheDeprecated)
- (void)setHighlightedImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:`");
- (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:`");
- (void)setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:completed:`");
- (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:completed:`");
- (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:progress:completed:`");
- (void)cancelCurrentHighlightedImageLoad __deprecated_msg("Use `sd_cancelCurrentHighlightedImageLoad`");
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/UIImageView+HighlightedWebCache.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,055
|
```objective-c
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDWebImageDownloaderOperation.h"
#import "SDWebImageDecoder.h"
#import "UIImage+MultiFormat.h"
#import <ImageIO/ImageIO.h>
#import "SDWebImageManager.h"
@interface SDWebImageDownloaderOperation () <NSURLConnectionDataDelegate>
@property (copy, nonatomic) SDWebImageDownloaderProgressBlock progressBlock;
@property (copy, nonatomic) SDWebImageDownloaderCompletedBlock completedBlock;
@property (copy, nonatomic) SDWebImageNoParamsBlock cancelBlock;
@property (assign, nonatomic, getter = isExecuting) BOOL executing;
@property (assign, nonatomic, getter = isFinished) BOOL finished;
@property (assign, nonatomic) NSInteger expectedSize;
@property (strong, nonatomic) NSMutableData *imageData;
@property (strong, nonatomic) NSURLConnection *connection;
@property (strong, atomic) NSThread *thread;
#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId;
#endif
@end
@implementation SDWebImageDownloaderOperation {
size_t width, height;
UIImageOrientation orientation;
BOOL responseFromCached;
}
@synthesize executing = _executing;
@synthesize finished = _finished;
- (id)initWithRequest:(NSURLRequest *)request
options:(SDWebImageDownloaderOptions)options
progress:(SDWebImageDownloaderProgressBlock)progressBlock
completed:(SDWebImageDownloaderCompletedBlock)completedBlock
cancelled:(SDWebImageNoParamsBlock)cancelBlock {
if ((self = [super init])) {
_request = request;
_shouldDecompressImages = YES;
_shouldUseCredentialStorage = YES;
_options = options;
_progressBlock = [progressBlock copy];
_completedBlock = [completedBlock copy];
_cancelBlock = [cancelBlock copy];
_executing = NO;
_finished = NO;
_expectedSize = 0;
responseFromCached = YES; // Initially wrong until `connection:willCacheResponse:` is called or not called
}
return self;
}
- (void)start {
@synchronized (self) {
if (self.isCancelled) {
self.finished = YES;
[self reset];
return;
}
#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
if ([self shouldContinueWhenAppEntersBackground]) {
__weak __typeof__ (self) wself = self;
self.backgroundTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
__strong __typeof (wself) sself = wself;
if (sself) {
[sself cancel];
[[UIApplication sharedApplication] endBackgroundTask:sself.backgroundTaskId];
sself.backgroundTaskId = UIBackgroundTaskInvalid;
}
}];
}
#endif
self.executing = YES;
self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
self.thread = [NSThread currentThread];
}
[self.connection start];
if (self.connection) {
if (self.progressBlock) {
self.progressBlock(0, NSURLResponseUnknownLength);
}
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:self];
});
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_5_1) {
// Make sure to run the runloop in our background thread so it can process downloaded data
// Note: we use a timeout to work around an issue with NSURLConnection cancel under iOS 5
// not waking up the runloop, leading to dead threads (see path_to_url
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false);
}
else {
CFRunLoopRun();
}
if (!self.isFinished) {
[self.connection cancel];
[self connection:self.connection didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorTimedOut userInfo:@{NSURLErrorFailingURLErrorKey : self.request.URL}]];
}
}
else {
if (self.completedBlock) {
self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Connection can't be initialized"}], YES);
}
}
#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
if (self.backgroundTaskId != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskId];
self.backgroundTaskId = UIBackgroundTaskInvalid;
}
#endif
}
- (void)cancel {
@synchronized (self) {
if (self.thread) {
[self performSelector:@selector(cancelInternalAndStop) onThread:self.thread withObject:nil waitUntilDone:NO];
}
else {
[self cancelInternal];
}
}
}
- (void)cancelInternalAndStop {
if (self.isFinished) return;
[self cancelInternal];
CFRunLoopStop(CFRunLoopGetCurrent());
}
- (void)cancelInternal {
if (self.isFinished) return;
[super cancel];
if (self.cancelBlock) self.cancelBlock();
if (self.connection) {
[self.connection cancel];
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self];
});
// As we cancelled the connection, its callback won't be called and thus won't
// maintain the isFinished and isExecuting flags.
if (self.isExecuting) self.executing = NO;
if (!self.isFinished) self.finished = YES;
}
[self reset];
}
- (void)done {
self.finished = YES;
self.executing = NO;
[self reset];
}
- (void)reset {
self.cancelBlock = nil;
self.completedBlock = nil;
self.progressBlock = nil;
self.connection = nil;
self.imageData = nil;
self.thread = nil;
}
- (void)setFinished:(BOOL)finished {
[self willChangeValueForKey:@"isFinished"];
_finished = finished;
[self didChangeValueForKey:@"isFinished"];
}
- (void)setExecuting:(BOOL)executing {
[self willChangeValueForKey:@"isExecuting"];
_executing = executing;
[self didChangeValueForKey:@"isExecuting"];
}
- (BOOL)isConcurrent {
return YES;
}
#pragma mark NSURLConnection (delegate)
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
//'304 Not Modified' is an exceptional one
if ((![response respondsToSelector:@selector(statusCode)] || [((NSHTTPURLResponse *)response) statusCode] < 400) && [((NSHTTPURLResponse *)response) statusCode] != 304) {
NSInteger expected = response.expectedContentLength > 0 ? (NSInteger)response.expectedContentLength : 0;
self.expectedSize = expected;
if (self.progressBlock) {
self.progressBlock(0, expected);
}
self.imageData = [[NSMutableData alloc] initWithCapacity:expected];
}
else {
NSUInteger code = [((NSHTTPURLResponse *)response) statusCode];
//This is the case when server returns '304 Not Modified'. It means that remote image is not changed.
//In case of 304 we need just cancel the operation and return cached image from the cache.
if (code == 304) {
[self cancelInternal];
} else {
[self.connection cancel];
}
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil];
});
if (self.completedBlock) {
self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:[((NSHTTPURLResponse *)response) statusCode] userInfo:nil], YES);
}
CFRunLoopStop(CFRunLoopGetCurrent());
[self done];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.imageData appendData:data];
if ((self.options & SDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0 && self.completedBlock) {
// The following code is from path_to_url
// Thanks to the author @Nyx0uf
// Get the total bytes downloaded
const NSInteger totalSize = self.imageData.length;
// Update the data source, we must pass ALL the data, not just the new bytes
CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)self.imageData, NULL);
if (width + height == 0) {
CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL);
if (properties) {
NSInteger orientationValue = -1;
CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight);
if (val) CFNumberGetValue(val, kCFNumberLongType, &height);
val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth);
if (val) CFNumberGetValue(val, kCFNumberLongType, &width);
val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation);
if (val) CFNumberGetValue(val, kCFNumberNSIntegerType, &orientationValue);
CFRelease(properties);
// When we draw to Core Graphics, we lose orientation information,
// which means the image below born of initWithCGIImage will be
// oriented incorrectly sometimes. (Unlike the image born of initWithData
// in connectionDidFinishLoading.) So save it here and pass it on later.
orientation = [[self class] orientationFromPropertyValue:(orientationValue == -1 ? 1 : orientationValue)];
}
}
if (width + height > 0 && totalSize < self.expectedSize) {
// Create the image
CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
#ifdef TARGET_OS_IPHONE
// Workaround for iOS anamorphic image
if (partialImageRef) {
const size_t partialHeight = CGImageGetHeight(partialImageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace);
if (bmContext) {
CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = partialHeight}, partialImageRef);
CGImageRelease(partialImageRef);
partialImageRef = CGBitmapContextCreateImage(bmContext);
CGContextRelease(bmContext);
}
else {
CGImageRelease(partialImageRef);
partialImageRef = nil;
}
}
#endif
if (partialImageRef) {
UIImage *image = [UIImage imageWithCGImage:partialImageRef scale:1 orientation:orientation];
NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL];
UIImage *scaledImage = [self scaledImageForKey:key image:image];
if (self.shouldDecompressImages) {
image = [UIImage decodedImageWithImage:scaledImage];
}
else {
image = scaledImage;
}
CGImageRelease(partialImageRef);
dispatch_main_sync_safe(^{
if (self.completedBlock) {
self.completedBlock(image, nil, nil, NO);
}
});
}
}
CFRelease(imageSource);
}
if (self.progressBlock) {
self.progressBlock(self.imageData.length, self.expectedSize);
}
}
+ (UIImageOrientation)orientationFromPropertyValue:(NSInteger)value {
switch (value) {
case 1:
return UIImageOrientationUp;
case 3:
return UIImageOrientationDown;
case 8:
return UIImageOrientationLeft;
case 6:
return UIImageOrientationRight;
case 2:
return UIImageOrientationUpMirrored;
case 4:
return UIImageOrientationDownMirrored;
case 5:
return UIImageOrientationLeftMirrored;
case 7:
return UIImageOrientationRightMirrored;
default:
return UIImageOrientationUp;
}
}
- (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image {
return SDScaledImageForKey(key, image);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection {
SDWebImageDownloaderCompletedBlock completionBlock = self.completedBlock;
@synchronized(self) {
CFRunLoopStop(CFRunLoopGetCurrent());
self.thread = nil;
self.connection = nil;
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil];
});
}
if (![[NSURLCache sharedURLCache] cachedResponseForRequest:_request]) {
responseFromCached = NO;
}
if (completionBlock) {
if (self.options & SDWebImageDownloaderIgnoreCachedResponse && responseFromCached) {
completionBlock(nil, nil, nil, YES);
}
else {
UIImage *image = [UIImage sd_imageWithData:self.imageData];
NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL];
image = [self scaledImageForKey:key image:image];
// Do not force decoding animated GIFs
if (!image.images) {
if (self.shouldDecompressImages) {
image = [UIImage decodedImageWithImage:image];
}
}
if (CGSizeEqualToSize(image.size, CGSizeZero)) {
completionBlock(nil, nil, [NSError errorWithDomain:@"SDWebImageErrorDomain" code:0 userInfo:@{NSLocalizedDescriptionKey : @"Downloaded image has 0 pixels"}], YES);
}
else {
completionBlock(image, self.imageData, nil, YES);
}
}
}
self.completionBlock = nil;
[self done];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
@synchronized(self) {
CFRunLoopStop(CFRunLoopGetCurrent());
self.thread = nil;
self.connection = nil;
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil];
});
}
if (self.completedBlock) {
self.completedBlock(nil, nil, error, YES);
}
self.completionBlock = nil;
[self done];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
responseFromCached = NO; // If this method is called, it means the response wasn't read from cache
if (self.request.cachePolicy == NSURLRequestReloadIgnoringLocalCacheData) {
// Prevents caching of responses
return nil;
}
else {
return cachedResponse;
}
}
- (BOOL)shouldContinueWhenAppEntersBackground {
return self.options & SDWebImageDownloaderContinueInBackground;
}
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection {
return self.shouldUseCredentialStorage;
}
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if (!(self.options & SDWebImageDownloaderAllowInvalidSSLCertificates) &&
[challenge.sender respondsToSelector:@selector(performDefaultHandlingForAuthenticationChallenge:)]) {
[challenge.sender performDefaultHandlingForAuthenticationChallenge:challenge];
} else {
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
} else {
if ([challenge previousFailureCount] == 0) {
if (self.credential) {
[[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge];
} else {
[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
}
} else {
[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
}
}
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/SDWebImageDownloaderOperation.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 3,574
|
```objective-c
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "UIButton+WebCache.h"
#import "objc/runtime.h"
#import "UIView+WebCacheOperation.h"
static char imageURLStorageKey;
@implementation UIButton (WebCache)
- (NSURL *)sd_currentImageURL {
NSURL *url = self.imageURLStorage[@(self.state)];
if (!url) {
url = self.imageURLStorage[@(UIControlStateNormal)];
}
return url;
}
- (NSURL *)sd_imageURLForState:(UIControlState)state {
return self.imageURLStorage[@(state)];
}
- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state {
[self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
}
- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder {
[self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
}
- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
[self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil];
}
- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock {
[self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock];
}
- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock {
[self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock];
}
- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {
[self setImage:placeholder forState:state];
[self sd_cancelImageLoadForState:state];
if (!url) {
[self.imageURLStorage removeObjectForKey:@(state)];
dispatch_main_async_safe(^{
NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
if (completedBlock) {
completedBlock(nil, error, SDImageCacheTypeNone, url);
}
});
return;
}
self.imageURLStorage[@(state)] = url;
__weak UIButton *wself = self;
id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (!wself) return;
dispatch_main_sync_safe(^{
__strong UIButton *sself = wself;
if (!sself) return;
if (image) {
[sself setImage:image forState:state];
}
if (completedBlock && finished) {
completedBlock(image, error, cacheType, url);
}
});
}];
[self sd_setImageLoadOperation:operation forState:state];
}
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
}
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
}
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil];
}
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock];
}
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock];
}
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {
[self sd_cancelImageLoadForState:state];
[self setBackgroundImage:placeholder forState:state];
if (url) {
__weak UIButton *wself = self;
id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (!wself) return;
dispatch_main_sync_safe(^{
__strong UIButton *sself = wself;
if (!sself) return;
if (image) {
[sself setBackgroundImage:image forState:state];
}
if (completedBlock && finished) {
completedBlock(image, error, cacheType, url);
}
});
}];
[self sd_setBackgroundImageLoadOperation:operation forState:state];
} else {
dispatch_main_async_safe(^{
NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
if (completedBlock) {
completedBlock(nil, error, SDImageCacheTypeNone, url);
}
});
}
}
- (void)sd_setImageLoadOperation:(id<SDWebImageOperation>)operation forState:(UIControlState)state {
[self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]];
}
- (void)sd_cancelImageLoadForState:(UIControlState)state {
[self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]];
}
- (void)sd_setBackgroundImageLoadOperation:(id<SDWebImageOperation>)operation forState:(UIControlState)state {
[self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]];
}
- (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state {
[self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]];
}
- (NSMutableDictionary *)imageURLStorage {
NSMutableDictionary *storage = objc_getAssociatedObject(self, &imageURLStorageKey);
if (!storage)
{
storage = [NSMutableDictionary dictionary];
objc_setAssociatedObject(self, &imageURLStorageKey, storage, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return storage;
}
@end
@implementation UIButton (WebCacheDeprecated)
- (NSURL *)currentImageURL {
return [self sd_currentImageURL];
}
- (NSURL *)imageURLForState:(UIControlState)state {
return [self sd_imageURLForState:state];
}
- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state {
[self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
}
- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder {
[self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
}
- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
[self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil];
}
- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock {
[self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (completedBlock) {
completedBlock(image, error, cacheType);
}
}];
}
- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock {
[self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (completedBlock) {
completedBlock(image, error, cacheType);
}
}];
}
- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock {
[self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (completedBlock) {
completedBlock(image, error, cacheType);
}
}];
}
- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
}
- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
}
- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil];
}
- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (completedBlock) {
completedBlock(image, error, cacheType);
}
}];
}
- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (completedBlock) {
completedBlock(image, error, cacheType);
}
}];
}
- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock {
[self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (completedBlock) {
completedBlock(image, error, cacheType);
}
}];
}
- (void)cancelCurrentImageLoad {
// in a backwards compatible manner, cancel for current state
[self sd_cancelImageLoadForState:self.state];
}
- (void)cancelBackgroundImageLoadForState:(UIControlState)state {
[self sd_cancelBackgroundImageLoadForState:state];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/UIButton+WebCache.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 2,582
|
```objective-c
//
//
//
// Created by kimziv on 13-9-14.
//
#ifndef _PinyinHelper_H_
#define _PinyinHelper_H_
typedef void(^OutputStringBlock)(NSString *pinYin) ;
typedef void(^OutputArrayBlock)(NSArray *array) ;
@class HanyuPinyinOutputFormat;
@interface PinyinHelper : NSObject {
}
/* async methods, "ui blocking" is gone, make ui update smoothly ,recommend use methods below*/
+ (void)toHanyuPinyinStringArrayWithChar:(unichar)ch
outputBlock:(OutputArrayBlock)outputBlock;
+ (void)toHanyuPinyinStringArrayWithChar:(unichar)ch
withHanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)outputFormat
outputBlock:(OutputArrayBlock)outputBlock;
+ (void)getFormattedHanyuPinyinStringArrayWithChar:(unichar)ch
withHanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)outputFormat
outputBlock:(OutputArrayBlock)outputBlock;
+ (void)getUnformattedHanyuPinyinStringArrayWithChar:(unichar)ch
outputBlock:(OutputArrayBlock)outputBlock;
+ (void)toTongyongPinyinStringArrayWithChar:(unichar)ch
outputBlock:(OutputArrayBlock)outputBlock;
+ (void)toWadeGilesPinyinStringArrayWithChar:(unichar)ch
outputBlock:(OutputArrayBlock)outputBlock;
+ (void)toMPS2PinyinStringArrayWithChar:(unichar)ch
outputBlock:(OutputArrayBlock)outputBlock;
+ (void)toYalePinyinStringArrayWithChar:(unichar)ch
outputBlock:(OutputArrayBlock)outputBlock;
+ (void)convertToTargetPinyinStringArrayWithChar:(unichar)ch
withPinyinRomanizationType:(NSString *)targetPinyinSystem
outputBlock:(OutputArrayBlock)outputBlock;
+ (void)toGwoyeuRomatzyhStringArrayWithChar:(unichar)ch
outputBlock:(OutputArrayBlock)outputBlock;
+ (void)convertToGwoyeuRomatzyhStringArrayWithChar:(unichar)ch
outputBlock:(OutputArrayBlock)outputBlock;
+ (void)toHanyuPinyinStringWithNSString:(NSString *)str
withHanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)outputFormat
withNSString:(NSString *)seperater
outputBlock:(OutputStringBlock)outputBlock;
+ (void)getFirstHanyuPinyinStringWithChar:(unichar)ch
withHanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)outputFormat
outputBlock:(OutputStringBlock)outputBlock;
/* sync methods */
+ (NSArray *)toHanyuPinyinStringArrayWithChar:(unichar)ch;
+ (NSArray *)toHanyuPinyinStringArrayWithChar:(unichar)ch
withHanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)outputFormat;
+ (NSArray *)getFormattedHanyuPinyinStringArrayWithChar:(unichar)ch
withHanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)outputFormat;
+ (NSArray *)getUnformattedHanyuPinyinStringArrayWithChar:(unichar)ch;
+ (NSArray *)toTongyongPinyinStringArrayWithChar:(unichar)ch;
+ (NSArray *)toWadeGilesPinyinStringArrayWithChar:(unichar)ch;
+ (NSArray *)toMPS2PinyinStringArrayWithChar:(unichar)ch;
+ (NSArray *)toYalePinyinStringArrayWithChar:(unichar)ch;
+ (NSArray *)convertToTargetPinyinStringArrayWithChar:(unichar)ch
withPinyinRomanizationType:(NSString *)targetPinyinSystem;
+ (NSArray *)toGwoyeuRomatzyhStringArrayWithChar:(unichar)ch;
+ (NSArray *)convertToGwoyeuRomatzyhStringArrayWithChar:(unichar)ch;
+ (NSString *)toHanyuPinyinStringWithNSString:(NSString *)str
withHanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)outputFormat
withNSString:(NSString *)seperater;
+ (NSString *)getFirstHanyuPinyinStringWithChar:(unichar)ch
withHanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)outputFormat;
+ (BOOL)isIncludeChineseInString:(NSString*)str;
@end
#endif // _PinyinHelper_H_
```
|
/content/code_sandbox/WeChat/ThirdLib/PinYin4Objc/Classes/PinyinHelper.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,045
|
```objective-c
//
//
//
// Created by kimziv on 13-9-14.
//
#include "ChineseToPinyinResource.h"
#define LEFT_BRACKET @"("
#define RIGHT_BRACKET @")"
#define COMMA @","
#ifdef DEBUG
#define PYLog(...) NSLog(__VA_ARGS__)
#else
#define PYLog(__unused ...)
#endif
#define kCacheKeyForUnicode2Pinyin @"UnicodeToPinyin"
static inline NSString* cachePathForKey(NSString* directory, NSString* key) {
return [directory stringByAppendingPathComponent:key];
}
@interface ChineseToPinyinResource ()
- (id<NSCoding>)cachedObjectForKey:(NSString*)key;
-(void)cacheObjec:(id<NSCoding>)obj forKey:(NSString *)key;
@end
@implementation ChineseToPinyinResource
- (id)init {
if (self = [super init]) {
_unicodeToHanyuPinyinTable = nil;
[self initializeResource];
}
return self;
}
- (void)initializeResource {
NSString* cachesDirectory = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
_directory = [[[cachesDirectory stringByAppendingPathComponent:[[NSBundle mainBundle] bundleIdentifier]] stringByAppendingPathComponent:@"PinYinCache"] copy];
NSFileManager *fileManager=[NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:_directory])
{
NSError *error=nil;
if (![fileManager createDirectoryAtPath:_directory withIntermediateDirectories:YES attributes:nil error:&error]) {
PYLog(@"Error, s is %@, %s, %s, %d",error.description, __FILE__ ,__FUNCTION__, __LINE__);
}
}
NSDictionary *dataMap=(NSDictionary *)[self cachedObjectForKey:kCacheKeyForUnicode2Pinyin];
if (dataMap) {
self->_unicodeToHanyuPinyinTable=dataMap;
}else{
NSString *resourceName =[[NSBundle mainBundle] pathForResource:@"unicode_to_hanyu_pinyin" ofType:@"txt"];
NSString *dictionaryText=[NSString stringWithContentsOfFile:resourceName encoding:NSUTF8StringEncoding error:nil];
NSArray *lines = [dictionaryText componentsSeparatedByString:@"\r\n"];
__block NSMutableDictionary *tempMap=[[NSMutableDictionary alloc] init];
@autoreleasepool {
[lines enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSArray *lineComponents=[obj componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
[tempMap setObject:lineComponents[1] forKey:lineComponents[0]];
}];
}
self->_unicodeToHanyuPinyinTable=tempMap;
[self cacheObjec:self->_unicodeToHanyuPinyinTable forKey:kCacheKeyForUnicode2Pinyin];
}
}
- (id<NSCoding>)cachedObjectForKey:(NSString*)key
{
NSError *error=nil;
NSData *data = [NSData dataWithContentsOfFile:cachePathForKey(_directory, key) options:0 error:&error];
// NSAssert4((!error), @"Error, s is %@, %s, %s, %d",error.description, __FILE__ ,__FUNCTION__, __LINE__);
if (!error) {
if (data) {
return [NSKeyedUnarchiver unarchiveObjectWithData:data];
}
}
return nil;
}
-(void)cacheObjec:(id<NSCoding>)obj forKey:(NSString *)key
{
NSData* data= [NSKeyedArchiver archivedDataWithRootObject:obj];
NSString* cachePath = cachePathForKey(_directory, key);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSError *error=nil;
[data writeToFile:cachePath options:NSDataWritingAtomic error:&error];
if (error){
PYLog(@"Error, s is %@, %s, %s, %d",error.description, __FILE__ ,__FUNCTION__, __LINE__);
}
});
}
- (NSArray *)getHanyuPinyinStringArrayWithChar:(unichar)ch {
NSString *pinyinRecord = [self getHanyuPinyinRecordFromCharWithChar:ch];
if (nil != pinyinRecord) {
NSRange rangeOfLeftBracket= [pinyinRecord rangeOfString:LEFT_BRACKET];
NSRange rangeOfRightBracket= [pinyinRecord rangeOfString:RIGHT_BRACKET];
NSString *stripedString = [pinyinRecord substringWithRange:NSMakeRange(rangeOfLeftBracket.location+rangeOfLeftBracket.length, rangeOfRightBracket.location-rangeOfLeftBracket.location-rangeOfLeftBracket.length)];
return [stripedString componentsSeparatedByString:COMMA];
}
else return nil;
}
- (BOOL)isValidRecordWithNSString:(NSString *)record {
NSString *noneStr = @"(none0)";
if ((nil != record) && ![record isEqual:noneStr] && [record hasPrefix:LEFT_BRACKET] && [record hasSuffix:RIGHT_BRACKET]) {
return YES;
}
else return NO;
}
- (NSString *)getHanyuPinyinRecordFromCharWithChar:(unichar)ch {
int codePointOfChar = ch;
NSString *codepointHexStr =[[NSString stringWithFormat:@"%x", codePointOfChar] uppercaseString];
NSString *foundRecord =[self->_unicodeToHanyuPinyinTable objectForKey:codepointHexStr];
return [self isValidRecordWithNSString:foundRecord] ? foundRecord : nil;
}
+ (ChineseToPinyinResource *)getInstance {
static ChineseToPinyinResource *sharedInstance=nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance=[[self alloc] init];
});
return sharedInstance;
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/PinYin4Objc/Classes/ChineseToPinyinResource.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,212
|
```objective-c
//
//
//
// Created by kimziv on 13-9-14.
//
#ifndef _PinyinFormatter_H_
#define _PinyinFormatter_H_
@class HanyuPinyinOutputFormat;
@interface PinyinFormatter : NSObject {
}
+ (NSString *)formatHanyuPinyinWithNSString:(NSString *)pinyinStr
withHanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)outputFormat;
+ (NSString *)convertToneNumber2ToneMarkWithNSString:(NSString *)pinyinStr;
- (id)init;
@end
#endif // _PinyinFormatter_H_
```
|
/content/code_sandbox/WeChat/ThirdLib/PinYin4Objc/Classes/PinyinFormatter.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 128
|
```objective-c
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageCache.h"
#import "SDWebImageDecoder.h"
#import "UIImage+MultiFormat.h"
#import <CommonCrypto/CommonDigest.h>
static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week
// PNG signature bytes and data (below)
static unsigned char kPNGSignatureBytes[8] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
static NSData *kPNGSignatureData = nil;
BOOL ImageDataHasPNGPreffix(NSData *data);
BOOL ImageDataHasPNGPreffix(NSData *data) {
NSUInteger pngSignatureLength = [kPNGSignatureData length];
if ([data length] >= pngSignatureLength) {
if ([[data subdataWithRange:NSMakeRange(0, pngSignatureLength)] isEqualToData:kPNGSignatureData]) {
return YES;
}
}
return NO;
}
@interface SDImageCache ()
@property (strong, nonatomic) NSCache *memCache;
@property (strong, nonatomic) NSString *diskCachePath;
@property (strong, nonatomic) NSMutableArray *customPaths;
@property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t ioQueue;
@end
@implementation SDImageCache {
NSFileManager *_fileManager;
}
+ (SDImageCache *)sharedImageCache {
static dispatch_once_t once;
static id instance;
dispatch_once(&once, ^{
instance = [self new];
});
return instance;
}
- (id)init {
return [self initWithNamespace:@"default"];
}
- (id)initWithNamespace:(NSString *)ns {
if ((self = [super init])) {
NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns];
// initialise PNG signature data
kPNGSignatureData = [NSData dataWithBytes:kPNGSignatureBytes length:8];
// Create IO serial queue
_ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL);
// Init default values
_maxCacheAge = kDefaultCacheMaxCacheAge;
// Init the memory cache
_memCache = [[NSCache alloc] init];
_memCache.name = fullNamespace;
// Init the disk cache
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
_diskCachePath = [paths[0] stringByAppendingPathComponent:fullNamespace];
// Set decompression to YES
_shouldDecompressImages = YES;
dispatch_sync(_ioQueue, ^{
_fileManager = [NSFileManager new];
});
#if TARGET_OS_IPHONE
// Subscribe to app events
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(clearMemory)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(cleanDisk)
name:UIApplicationWillTerminateNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(backgroundCleanDisk)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
#endif
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
SDDispatchQueueRelease(_ioQueue);
}
- (void)addReadOnlyCachePath:(NSString *)path {
if (!self.customPaths) {
self.customPaths = [NSMutableArray new];
}
if (![self.customPaths containsObject:path]) {
[self.customPaths addObject:path];
}
}
- (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path {
NSString *filename = [self cachedFileNameForKey:key];
return [path stringByAppendingPathComponent:filename];
}
- (NSString *)defaultCachePathForKey:(NSString *)key {
return [self cachePathForKey:key inPath:self.diskCachePath];
}
#pragma mark SDImageCache (private)
- (NSString *)cachedFileNameForKey:(NSString *)key {
const char *str = [key UTF8String];
if (str == NULL) {
str = "";
}
unsigned char r[CC_MD5_DIGEST_LENGTH];
CC_MD5(str, (CC_LONG)strlen(str), r);
NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
return filename;
}
#pragma mark ImageCache
- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk {
if (!image || !key) {
return;
}
[self.memCache setObject:image forKey:key cost:image.size.height * image.size.width * image.scale * image.scale];
if (toDisk) {
dispatch_async(self.ioQueue, ^{
NSData *data = imageData;
if (image && (recalculate || !data)) {
#if TARGET_OS_IPHONE
// We need to determine if the image is a PNG or a JPEG
// PNGs are easier to detect because they have a unique signature (path_to_url
// The first eight bytes of a PNG file always contain the following (decimal) values:
// 137 80 78 71 13 10 26 10
// We assume the image is PNG, in case the imageData is nil (i.e. if trying to save a UIImage directly),
// we will consider it PNG to avoid loosing the transparency
BOOL imageIsPng = YES;
// But if we have an image data, we will look at the preffix
if ([imageData length] >= [kPNGSignatureData length]) {
imageIsPng = ImageDataHasPNGPreffix(imageData);
}
if (imageIsPng) {
data = UIImagePNGRepresentation(image);
}
else {
data = UIImageJPEGRepresentation(image, (CGFloat)1.0);
}
#else
data = [NSBitmapImageRep representationOfImageRepsInArray:image.representations usingType: NSJPEGFileType properties:nil];
#endif
}
if (data) {
if (![_fileManager fileExistsAtPath:_diskCachePath]) {
[_fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL];
}
[_fileManager createFileAtPath:[self defaultCachePathForKey:key] contents:data attributes:nil];
}
});
}
}
- (void)storeImage:(UIImage *)image forKey:(NSString *)key {
[self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:YES];
}
- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk {
[self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:toDisk];
}
- (BOOL)diskImageExistsWithKey:(NSString *)key {
BOOL exists = NO;
// this is an exception to access the filemanager on another queue than ioQueue, but we are using the shared instance
// from apple docs on NSFileManager: The methods of the shared NSFileManager object can be called from multiple threads safely.
exists = [[NSFileManager defaultManager] fileExistsAtPath:[self defaultCachePathForKey:key]];
return exists;
}
- (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock {
dispatch_async(_ioQueue, ^{
BOOL exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key]];
if (completionBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(exists);
});
}
});
}
- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key {
return [self.memCache objectForKey:key];
}
- (UIImage *)imageFromDiskCacheForKey:(NSString *)key {
// First check the in-memory cache...
UIImage *image = [self imageFromMemoryCacheForKey:key];
if (image) {
return image;
}
// Second check the disk cache...
UIImage *diskImage = [self diskImageForKey:key];
if (diskImage) {
CGFloat cost = diskImage.size.height * diskImage.size.width * diskImage.scale * diskImage.scale;
[self.memCache setObject:diskImage forKey:key cost:cost];
}
return diskImage;
}
- (NSData *)diskImageDataBySearchingAllPathsForKey:(NSString *)key {
NSString *defaultPath = [self defaultCachePathForKey:key];
NSData *data = [NSData dataWithContentsOfFile:defaultPath];
if (data) {
return data;
}
for (NSString *path in self.customPaths) {
NSString *filePath = [self cachePathForKey:key inPath:path];
NSData *imageData = [NSData dataWithContentsOfFile:filePath];
if (imageData) {
return imageData;
}
}
return nil;
}
- (UIImage *)diskImageForKey:(NSString *)key {
NSData *data = [self diskImageDataBySearchingAllPathsForKey:key];
if (data) {
UIImage *image = [UIImage sd_imageWithData:data];
image = [self scaledImageForKey:key image:image];
if (self.shouldDecompressImages) {
image = [UIImage decodedImageWithImage:image];
}
return image;
}
else {
return nil;
}
}
- (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image {
return SDScaledImageForKey(key, image);
}
- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock {
if (!doneBlock) {
return nil;
}
if (!key) {
doneBlock(nil, SDImageCacheTypeNone);
return nil;
}
// First check the in-memory cache...
UIImage *image = [self imageFromMemoryCacheForKey:key];
if (image) {
doneBlock(image, SDImageCacheTypeMemory);
return nil;
}
NSOperation *operation = [NSOperation new];
dispatch_async(self.ioQueue, ^{
if (operation.isCancelled) {
return;
}
@autoreleasepool {
UIImage *diskImage = [self diskImageForKey:key];
if (diskImage) {
CGFloat cost = diskImage.size.height * diskImage.size.width * diskImage.scale * diskImage.scale;
[self.memCache setObject:diskImage forKey:key cost:cost];
}
dispatch_async(dispatch_get_main_queue(), ^{
doneBlock(diskImage, SDImageCacheTypeDisk);
});
}
});
return operation;
}
- (void)removeImageForKey:(NSString *)key {
[self removeImageForKey:key withCompletion:nil];
}
- (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion {
[self removeImageForKey:key fromDisk:YES withCompletion:completion];
}
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk {
[self removeImageForKey:key fromDisk:fromDisk withCompletion:nil];
}
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion {
if (key == nil) {
return;
}
[self.memCache removeObjectForKey:key];
if (fromDisk) {
dispatch_async(self.ioQueue, ^{
[_fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil];
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion();
});
}
});
} else if (completion){
completion();
}
}
- (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost {
self.memCache.totalCostLimit = maxMemoryCost;
}
- (NSUInteger)maxMemoryCost {
return self.memCache.totalCostLimit;
}
- (void)clearMemory {
[self.memCache removeAllObjects];
}
- (void)clearDisk {
[self clearDiskOnCompletion:nil];
}
- (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion
{
dispatch_async(self.ioQueue, ^{
[_fileManager removeItemAtPath:self.diskCachePath error:nil];
[_fileManager createDirectoryAtPath:self.diskCachePath
withIntermediateDirectories:YES
attributes:nil
error:NULL];
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion();
});
}
});
}
- (void)cleanDisk {
[self cleanDiskWithCompletionBlock:nil];
}
- (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock {
dispatch_async(self.ioQueue, ^{
NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
NSArray *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey];
// This enumerator prefetches useful properties for our cache files.
NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL
includingPropertiesForKeys:resourceKeys
options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:NULL];
NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.maxCacheAge];
NSMutableDictionary *cacheFiles = [NSMutableDictionary dictionary];
NSUInteger currentCacheSize = 0;
// Enumerate all of the files in the cache directory. This loop has two purposes:
//
// 1. Removing files that are older than the expiration date.
// 2. Storing file attributes for the size-based cleanup pass.
NSMutableArray *urlsToDelete = [[NSMutableArray alloc] init];
for (NSURL *fileURL in fileEnumerator) {
NSDictionary *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:NULL];
// Skip directories.
if ([resourceValues[NSURLIsDirectoryKey] boolValue]) {
continue;
}
// Remove files that are older than the expiration date;
NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey];
if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) {
[urlsToDelete addObject:fileURL];
continue;
}
// Store a reference to this file and account for its total size.
NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
currentCacheSize += [totalAllocatedSize unsignedIntegerValue];
[cacheFiles setObject:resourceValues forKey:fileURL];
}
for (NSURL *fileURL in urlsToDelete) {
[_fileManager removeItemAtURL:fileURL error:nil];
}
// If our remaining disk cache exceeds a configured maximum size, perform a second
// size-based cleanup pass. We delete the oldest files first.
if (self.maxCacheSize > 0 && currentCacheSize > self.maxCacheSize) {
// Target half of our maximum cache size for this cleanup pass.
const NSUInteger desiredCacheSize = self.maxCacheSize / 2;
// Sort the remaining cache files by their last modification time (oldest first).
NSArray *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent
usingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]];
}];
// Delete files until we fall below our desired cache size.
for (NSURL *fileURL in sortedFiles) {
if ([_fileManager removeItemAtURL:fileURL error:nil]) {
NSDictionary *resourceValues = cacheFiles[fileURL];
NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
currentCacheSize -= [totalAllocatedSize unsignedIntegerValue];
if (currentCacheSize < desiredCacheSize) {
break;
}
}
}
}
if (completionBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock();
});
}
});
}
- (void)backgroundCleanDisk {
UIApplication *application = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
// Clean up any unfinished task business by marking where you
// stopped or ending the task outright.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
[self cleanDiskWithCompletionBlock:^{
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
}
- (NSUInteger)getSize {
__block NSUInteger size = 0;
dispatch_sync(self.ioQueue, ^{
NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
for (NSString *fileName in fileEnumerator) {
NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName];
NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
size += [attrs fileSize];
}
});
return size;
}
- (NSUInteger)getDiskCount {
__block NSUInteger count = 0;
dispatch_sync(self.ioQueue, ^{
NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
count = [[fileEnumerator allObjects] count];
});
return count;
}
- (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock {
NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
dispatch_async(self.ioQueue, ^{
NSUInteger fileCount = 0;
NSUInteger totalSize = 0;
NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL
includingPropertiesForKeys:@[NSFileSize]
options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:NULL];
for (NSURL *fileURL in fileEnumerator) {
NSNumber *fileSize;
[fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL];
totalSize += [fileSize unsignedIntegerValue];
fileCount += 1;
}
if (completionBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(fileCount, totalSize);
});
}
});
}
- (float)checkTmpSize {
float totalSize = 0;
NSDirectoryEnumerator *fileEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:_diskCachePath];
for (NSString *fileName in fileEnumerator) {
NSString *filePath = [_diskCachePath stringByAppendingPathComponent:fileName];
NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
unsigned long long length = [attrs fileSize];
totalSize += length / 1024.0 / 1024.0;
} //
NSLog(@"tmp size is %.2f",totalSize);
return totalSize;
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/SDWebImage/SDImageCache.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 4,189
|
```objective-c
//
// NSString+PinYin4Cocoa.m
// PinYin4Cocoa
//
// Created by kimziv on 13-9-15.
//
#import "NSString+PinYin4Cocoa.h"
#ifdef DEBUG
#define PYLog(...) NSLog(__VA_ARGS__)
#else
#define PYLog(__unused ...)
#endif
@implementation NSString (PinYin4Cocoa)
- (NSInteger)indexOfString:(NSString *)s {
NSAssert3((s!=nil), @"Error, s is a nil string, %s, %s, %d", __FILE__, __FUNCTION__, __LINE__);
if ([s length] == 0) {
return 0;
}
NSRange range = [self rangeOfString:s];
return range.location == NSNotFound ? -1 : (int) range.location;
}
- (NSInteger)indexOfString:(NSString *)s fromIndex:(int)index {
NSAssert3((s!=nil), @"Error, s is a nil string, %s, %s, %d", __FILE__, __FUNCTION__, __LINE__);
if ([s length] == 0) {
return 0;
}
NSRange searchRange = NSMakeRange((NSUInteger) index,
[self length] - (NSUInteger) index);
NSRange range = [self rangeOfString:s
options:NSLiteralSearch
range:searchRange];
return range.location == NSNotFound ? -1 : (int) range.location;
}
- (NSInteger)indexOf:(int)ch {
// unichar c = (unichar) ch;
// for(int i=0;i<self.length;i++)
// if(c == [self characterAtIndex:i])
// return i;
// return -1;
return [self indexOf:ch fromIndex:0];
}
- (NSInteger)indexOf:(int)ch fromIndex:(int)index {
unichar c = (unichar) ch;
NSString *s = [NSString stringWithCharacters:&c length:1];
return [self indexOfString:s fromIndex:(int)index];
}
+ (NSString *)valueOfChar:(unichar)value {
return [NSString stringWithFormat:@"%C", value];
}
-(NSString *) stringByReplacingRegexPattern:(NSString *)regex withString:(NSString *) replacement caseInsensitive:(BOOL)ignoreCase {
return [self stringByReplacingRegexPattern:regex withString:replacement caseInsensitive:ignoreCase treatAsOneLine:NO];
}
-(NSString *) stringByReplacingRegexPattern:(NSString *)regex withString:(NSString *) replacement caseInsensitive:(BOOL) ignoreCase treatAsOneLine:(BOOL) assumeMultiLine {
NSUInteger options=0;
if (ignoreCase) {
options = options | NSRegularExpressionCaseInsensitive;
}
if (assumeMultiLine) {
options = options | NSRegularExpressionDotMatchesLineSeparators;
}
NSError *error=nil;
NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex options:options error:&error];
if (error) {
PYLog(@"Error creating Regex: %@",[error description]);
return nil;
}
NSString *retVal= [pattern stringByReplacingMatchesInString:self options:0 range:NSMakeRange(0, [self length]) withTemplate:replacement];
return retVal;
}
-(NSString *) stringByReplacingRegexPattern:(NSString *)regex withString:(NSString *) replacement {
return [self stringByReplacingRegexPattern:regex withString:replacement caseInsensitive:NO treatAsOneLine:NO];
}
-(NSArray *) stringsByExtractingGroupsUsingRegexPattern:(NSString *)regex caseInsensitive:(BOOL) ignoreCase treatAsOneLine:(BOOL) assumeMultiLine {
NSUInteger options=0;
if (ignoreCase) {
options = options | NSRegularExpressionCaseInsensitive;
}
if (assumeMultiLine) {
options = options | NSRegularExpressionDotMatchesLineSeparators;
}
NSError *error=nil;
NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex options:options error:&error];
if (error) {
PYLog(@"Error creating Regex: %@",[error description]);
return nil;
}
__block NSMutableArray *retVal = [NSMutableArray array];
[pattern enumerateMatchesInString:self options:0 range:NSMakeRange(0, [self length]) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
//Note, we only want to return the things in parens, so we're skipping index 0 intentionally
for (int i=1; i<[result numberOfRanges]; i++) {
NSString *matchedString=[self substringWithRange:[result rangeAtIndex:i]];
[retVal addObject:matchedString];
}
}];
return retVal;
}
-(NSArray *) stringsByExtractingGroupsUsingRegexPattern:(NSString *)regex {
return [self stringsByExtractingGroupsUsingRegexPattern:regex caseInsensitive:NO treatAsOneLine:NO];
}
-(BOOL) matchesPatternRegexPattern:(NSString *)regex caseInsensitive:(BOOL) ignoreCase treatAsOneLine:(BOOL) assumeMultiLine {
NSUInteger options=0;
if (ignoreCase) {
options = options | NSRegularExpressionCaseInsensitive;
}
if (assumeMultiLine) {
options = options | NSRegularExpressionDotMatchesLineSeparators;
}
NSError *error=nil;
NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex options:options error:&error];
if (error) {
PYLog(@"Error creating Regex: %@",[error description]);
return NO; //Can't possibly match an invalid Regex
}
return ([pattern numberOfMatchesInString:self options:0 range:NSMakeRange(0, [self length])] > 0);
}
-(BOOL) matchesPatternRegexPattern:(NSString *)regex {
return [self matchesPatternRegexPattern:regex caseInsensitive:NO treatAsOneLine:NO];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/PinYin4Objc/Classes/NSString+PinYin4Cocoa.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,235
|
```objective-c
//
//
//
// Created by kimziv on 13-9-14.
//
#include "HanyuPinyinOutputFormat.h"
@implementation HanyuPinyinOutputFormat
@synthesize vCharType=_vCharType;
@synthesize caseType=_caseType;
@synthesize toneType=_toneType;
- (id)init {
if (self = [super init]) {
[self restoreDefault];
}
return self;
}
- (void)restoreDefault {
_vCharType = VCharTypeWithUAndColon;
_caseType = CaseTypeLowercase;
_toneType = ToneTypeWithToneNumber;
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/PinYin4Objc/Classes/HanyuPinyinOutputFormat.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 138
|
```objective-c
/**
* Created by kimziv on 13-9-14.
*/
#ifndef _HanyuPinyinOutputFormat_H_
#define _HanyuPinyinOutputFormat_H_
typedef enum {
ToneTypeWithToneNumber,
ToneTypeWithoutTone,
ToneTypeWithToneMark
}ToneType;
typedef enum {
CaseTypeUppercase,
CaseTypeLowercase
}CaseType;
typedef enum {
VCharTypeWithUAndColon,
VCharTypeWithV,
VCharTypeWithUUnicode
}VCharType;
@interface HanyuPinyinOutputFormat : NSObject
@property(nonatomic, assign) VCharType vCharType;
@property(nonatomic, assign) CaseType caseType;
@property(nonatomic, assign) ToneType toneType;
- (id)init;
- (void)restoreDefault;
@end
#endif // _HanyuPinyinOutputFormat_H_
```
|
/content/code_sandbox/WeChat/ThirdLib/PinYin4Objc/Classes/HanyuPinyinOutputFormat.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 192
|
```objective-c
//
// NSString+PinYin4Cocoa.h
// PinYin4Cocoa
//
// Created by kimziv on 13-9-15.
//
#import <Foundation/Foundation.h>
@interface NSString (PinYin4Cocoa)
- (NSInteger)indexOfString:(NSString *)s;
- (NSInteger)indexOfString:(NSString *)s fromIndex:(int)index;
- (NSInteger)indexOf:(int)ch;
- (NSInteger)indexOf:(int)ch fromIndex:(int)index;
+ (NSString *)valueOfChar:(unichar)value;
-(NSString *) stringByReplacingRegexPattern:(NSString *)regex withString:(NSString *) replacement;
-(NSString *) stringByReplacingRegexPattern:(NSString *)regex withString:(NSString *) replacement caseInsensitive:(BOOL) ignoreCase;
-(NSString *) stringByReplacingRegexPattern:(NSString *)regex withString:(NSString *) replacement caseInsensitive:(BOOL) ignoreCase treatAsOneLine:(BOOL) assumeMultiLine;
-(NSArray *) stringsByExtractingGroupsUsingRegexPattern:(NSString *)regex;
-(NSArray *) stringsByExtractingGroupsUsingRegexPattern:(NSString *)regex caseInsensitive:(BOOL) ignoreCase treatAsOneLine:(BOOL) assumeMultiLine;
-(BOOL) matchesPatternRegexPattern:(NSString *)regex;
-(BOOL) matchesPatternRegexPattern:(NSString *)regex caseInsensitive:(BOOL) ignoreCase treatAsOneLine:(BOOL) assumeMultiLine;
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/PinYin4Objc/Classes/NSString+PinYin4Cocoa.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 287
|
```objective-c
//
// PinYin4Objc.h
// PinYin4ObjcExample
//
// Created by kimziv on 13-9-16.
//
//#ifndef PinYin4ObjcExample_PinYin4Objc_h
//#define PinYin4ObjcExample_PinYin4Objc_h
//
//
//
//#endif
#import "HanyuPinyinOutputFormat.h"
#import "PinyinHelper.h"
```
|
/content/code_sandbox/WeChat/ThirdLib/PinYin4Objc/Classes/PinYin4Objc.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 97
|
```objective-c
//
//
//
// Created by kimziv on 13-9-14.
//
#include "HanyuPinyinOutputFormat.h"
#include "PinyinFormatter.h"
#import "NSString+PinYin4Cocoa.h"
@interface PinyinFormatter ()
+(NSInteger)getNumericValue:(unichar)c;
+(NSInteger)indexOfChar:(int*) table ch:(unichar)c;
@end
@implementation PinyinFormatter
static int numericKeys[] = {
0x0030, 0x0041, 0x0061, 0x00b2, 0x00b9, 0x00bc, 0x0660, 0x06f0,
0x0966, 0x09e6, 0x09f4, 0x09f9, 0x0a66, 0x0ae6, 0x0b66, 0x0be7,
0x0bf1, 0x0bf2, 0x0c66, 0x0ce6, 0x0d66, 0x0e50, 0x0ed0, 0x0f20,
0x1040, 0x1369, 0x1373, 0x1374, 0x1375, 0x1376, 0x1377, 0x1378,
0x1379, 0x137a, 0x137b, 0x137c, 0x16ee, 0x17e0, 0x1810, 0x2070,
0x2074, 0x2080, 0x2153, 0x215f, 0x2160, 0x216c, 0x216d, 0x216e,
0x216f, 0x2170, 0x217c, 0x217d, 0x217e, 0x217f, 0x2180, 0x2181,
0x2182, 0x2460, 0x2474, 0x2488, 0x24ea, 0x2776, 0x2780, 0x278a,
0x3007, 0x3021, 0x3038, 0x3039, 0x303a, 0x3280, 0xff10, 0xff21,
0xff41,
};
static unichar numericValues[] = {
0x0039, 0x0030, 0x005a, 0x0037, 0x007a, 0x0057, 0x00b3, 0x00b0,
0x00b9, 0x00b8, 0x00be, 0x0000, 0x0669, 0x0660, 0x06f9, 0x06f0,
0x096f, 0x0966, 0x09ef, 0x09e6, 0x09f7, 0x09f3, 0x09f9, 0x09e9,
0x0a6f, 0x0a66, 0x0aef, 0x0ae6, 0x0b6f, 0x0b66, 0x0bf0, 0x0be6,
0x0bf1, 0x0b8d, 0x0bf2, 0x080a, 0x0c6f, 0x0c66, 0x0cef, 0x0ce6,
0x0d6f, 0x0d66, 0x0e59, 0x0e50, 0x0ed9, 0x0ed0, 0x0f29, 0x0f20,
0x1049, 0x1040, 0x1372, 0x1368, 0x1373, 0x135f, 0x1374, 0x1356,
0x1375, 0x134d, 0x1376, 0x1344, 0x1377, 0x133b, 0x1378, 0x1332,
0x1379, 0x1329, 0x137a, 0x1320, 0x137b, 0x1317, 0x137c, 0xec6c,
0x16f0, 0x16dd, 0x17e9, 0x17e0, 0x1819, 0x1810, 0x2070, 0x2070,
0x2079, 0x2070, 0x2089, 0x2080, 0x215e, 0x0000, 0x215f, 0x215e,
0x216b, 0x215f, 0x216c, 0x213a, 0x216d, 0x2109, 0x216e, 0x1f7a,
0x216f, 0x1d87, 0x217b, 0x216f, 0x217c, 0x214a, 0x217d, 0x2119,
0x217e, 0x1f8a, 0x217f, 0x1d97, 0x2180, 0x1d98, 0x2181, 0x0df9,
0x2182, 0xfa72, 0x2473, 0x245f, 0x2487, 0x2473, 0x249b, 0x2487,
0x24ea, 0x24ea, 0x277f, 0x2775, 0x2789, 0x277f, 0x2793, 0x2789,
0x3007, 0x3007, 0x3029, 0x3020, 0x3038, 0x302e, 0x3039, 0x3025,
0x303a, 0x301c, 0x3289, 0x327f, 0xff19, 0xff10, 0xff3a, 0xff17,
0xff5a, 0xff37,
};
+ (NSString *)formatHanyuPinyinWithNSString:(NSString *)pinyinStr
withHanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)outputFormat {
if ((ToneTypeWithToneMark == [outputFormat toneType]) && ((VCharTypeWithV == [outputFormat vCharType]) || (VCharTypeWithUAndColon == [outputFormat vCharType]))) {
@throw [NSException exceptionWithName:@"Throwing a BadHanyuPinyinOutputFormatCombination exception" reason:@"tone marks cannot be added to v or u:." userInfo:nil];
}
if (ToneTypeWithoutTone == [outputFormat toneType]) {
pinyinStr =[pinyinStr stringByReplacingOccurrencesOfString:@"[1-5]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, pinyinStr.length)];
}
else if (ToneTypeWithToneMark == [outputFormat toneType]) {
pinyinStr =[pinyinStr stringByReplacingOccurrencesOfString:@"u:" withString:@"v"];
pinyinStr = [PinyinFormatter convertToneNumber2ToneMarkWithNSString:pinyinStr];
}
if (VCharTypeWithV == [outputFormat vCharType]) {
pinyinStr =[pinyinStr stringByReplacingOccurrencesOfString:@"u:" withString:@"v"];
}
else if (VCharTypeWithUUnicode == [outputFormat vCharType]) {
pinyinStr =[pinyinStr stringByReplacingOccurrencesOfString:@"u:" withString:@""];
}
if (CaseTypeUppercase == [outputFormat caseType]) {
pinyinStr = [pinyinStr uppercaseString];
}
return pinyinStr;
}
+ (NSString *)convertToneNumber2ToneMarkWithNSString:(NSString *)pinyinStr {
NSString *lowerCasePinyinStr = [pinyinStr lowercaseString];
if ([lowerCasePinyinStr matchesPatternRegexPattern:@"[a-z]*[1-5]?"]) {
unichar defautlCharValue = '$';
int defautlIndexValue = -1;
unichar unmarkedVowel = defautlCharValue;
int indexOfUnmarkedVowel = defautlIndexValue;
unichar charA = 'a';
unichar charE = 'e';
NSString *ouStr = @"ou";
NSString *allUnmarkedVowelStr = @"aeiouv";
NSString *allMarkedVowelStr = @"aeiou";
if ([lowerCasePinyinStr matchesPatternRegexPattern:@"[a-z]*[1-5]"]) {
int tuneNumber = [PinyinFormatter getNumericValue:[lowerCasePinyinStr characterAtIndex:lowerCasePinyinStr.length -1]];
int indexOfA = [lowerCasePinyinStr indexOf:charA];
int indexOfE = [lowerCasePinyinStr indexOf:charE];
int ouIndex = [lowerCasePinyinStr indexOfString:ouStr];
if (-1 != indexOfA) {
indexOfUnmarkedVowel = indexOfA;
unmarkedVowel = charA;
}
else if (-1 != indexOfE) {
indexOfUnmarkedVowel = indexOfE;
unmarkedVowel = charE;
}
else if (-1 != ouIndex) {
indexOfUnmarkedVowel = ouIndex;
unmarkedVowel = [ouStr characterAtIndex:0];
}
else {
for (int i = [lowerCasePinyinStr length] - 1; i >= 0; i--) {
if ([[NSString valueOfChar:[lowerCasePinyinStr characterAtIndex:i]] matchesPatternRegexPattern:@"[aeiouv]"]) {
indexOfUnmarkedVowel = i;
unmarkedVowel = [lowerCasePinyinStr characterAtIndex:i];
break;
}
}
}
if ((defautlCharValue != unmarkedVowel) && (defautlIndexValue != indexOfUnmarkedVowel)) {
int rowIndex = [allUnmarkedVowelStr indexOf:unmarkedVowel];
int columnIndex = tuneNumber - 1;
int vowelLocation = rowIndex * 5 + columnIndex;
unichar markedVowel = [allMarkedVowelStr characterAtIndex:vowelLocation];
NSMutableString *resultBuffer = [[NSMutableString alloc] init];
[resultBuffer appendString:[[lowerCasePinyinStr substringToIndex:indexOfUnmarkedVowel+1] stringByReplacingOccurrencesOfString:@"v" withString:@""]];
[resultBuffer appendFormat:@"%C",markedVowel];
[resultBuffer appendString:[[lowerCasePinyinStr substringWithRange:NSMakeRange(indexOfUnmarkedVowel + 1, lowerCasePinyinStr.length-indexOfUnmarkedVowel)] stringByReplacingOccurrencesOfString:@"v" withString:@""]];
return [resultBuffer description];
}
else {
return lowerCasePinyinStr;
}
}
else {
return [lowerCasePinyinStr stringByReplacingOccurrencesOfString:@"v" withString:@""];
}
}
else {
return lowerCasePinyinStr;
}
}
+(NSInteger)getNumericValue:(unichar)c
{
if (c < 128) {
// Optimized for ASCII
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'a' && c <= 'z') {
return c - ('a' - 10);
}
if (c >= 'A' && c <= 'Z') {
return c - ('A' - 10);
}
return -1;
}
NSInteger result = [self indexOfChar:numericKeys ch:c];
if (result >= 0 && c <= numericValues[result * 2]) {
unichar difference = numericValues[result * 2 + 1];
if (difference == 0) {
return -2;
}
// Value is always positive, must be negative value
if (difference > c) {
return c - (short) difference;
}
return c - difference;
}
return -1;
}
+(NSInteger)indexOfChar:(int*) table ch:(unichar)c{
NSInteger len=sizeof(table)/sizeof(table[0]);
for (int i = 0; i < len; i++) {
if (table[i] == (int) c) {
return i;
}
}
return -1;
}
- (id)init {
return [super init];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/PinYin4Objc/Classes/PinyinFormatter.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 2,907
|
```objective-c
//
//
//
// Created by kimziv on 13-9-14.
//
#include "ChineseToPinyinResource.h"
#include "HanyuPinyinOutputFormat.h"
#include "PinyinFormatter.h"
#include "PinyinHelper.h"
#define HANYU_PINYIN @"Hanyu"
#define WADEGILES_PINYIN @"Wade"
#define MPS2_PINYIN @"MPSII"
#define YALE_PINYIN @"Yale"
#define TONGYONG_PINYIN @"Tongyong"
#define GWOYEU_ROMATZYH @"Gwoyeu"
@implementation PinyinHelper
//////async methods
+ (void)toHanyuPinyinStringArrayWithChar:(unichar)ch
outputBlock:(OutputArrayBlock)outputBlock
{
[PinyinHelper getUnformattedHanyuPinyinStringArrayWithChar:ch outputBlock:outputBlock];
}
+ (void)toHanyuPinyinStringArrayWithChar:(unichar)ch
withHanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)outputFormat
outputBlock:(OutputArrayBlock)outputBlock
{
return [PinyinHelper getFormattedHanyuPinyinStringArrayWithChar:ch withHanyuPinyinOutputFormat:outputFormat outputBlock:outputBlock];
}
+ (void)getFormattedHanyuPinyinStringArrayWithChar:(unichar)ch
withHanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)outputFormat
outputBlock:(OutputArrayBlock)outputBlock
{
[PinyinHelper getUnformattedHanyuPinyinStringArrayWithChar:ch outputBlock:^(NSArray *array) {
if (outputBlock) {
if (nil != array) {
NSMutableArray *targetPinyinStringArray = [NSMutableArray arrayWithCapacity:array.count];
for (int i = 0; i < (int) [array count]; i++) {
[targetPinyinStringArray replaceObjectAtIndex:i withObject:[PinyinFormatter formatHanyuPinyinWithNSString:
[array objectAtIndex:i]withHanyuPinyinOutputFormat:outputFormat]];
}
outputBlock(targetPinyinStringArray);
}
else{
outputBlock(nil);
}
}
}];
}
+ (void)getUnformattedHanyuPinyinStringArrayWithChar:(unichar)ch
outputBlock:(OutputArrayBlock)outputBlock
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSArray *array= [[ChineseToPinyinResource getInstance] getHanyuPinyinStringArrayWithChar:ch];
dispatch_async(dispatch_get_main_queue(), ^{
if (outputBlock) {
outputBlock(array);
}
});
});
}
+ (void)toTongyongPinyinStringArrayWithChar:(unichar)ch
outputBlock:(OutputArrayBlock)outputBlock
{
return [PinyinHelper convertToTargetPinyinStringArrayWithChar:ch withPinyinRomanizationType: TONGYONG_PINYIN outputBlock:outputBlock];
}
+ (void)toWadeGilesPinyinStringArrayWithChar:(unichar)ch
outputBlock:(OutputArrayBlock)outputBlock
{
[PinyinHelper convertToTargetPinyinStringArrayWithChar:ch withPinyinRomanizationType: WADEGILES_PINYIN outputBlock:outputBlock];
}
+ (void)toMPS2PinyinStringArrayWithChar:(unichar)ch
outputBlock:(OutputArrayBlock)outputBlock
{
[PinyinHelper convertToTargetPinyinStringArrayWithChar:ch withPinyinRomanizationType: MPS2_PINYIN outputBlock:outputBlock];
}
+ (void)toYalePinyinStringArrayWithChar:(unichar)ch
outputBlock:(OutputArrayBlock)outputBlock
{
[PinyinHelper convertToTargetPinyinStringArrayWithChar:ch withPinyinRomanizationType: YALE_PINYIN outputBlock:outputBlock];
}
+ (void)convertToTargetPinyinStringArrayWithChar:(unichar)ch
withPinyinRomanizationType:(NSString *)targetPinyinSystem
outputBlock:(OutputArrayBlock)outputBlock
{
[PinyinHelper getUnformattedHanyuPinyinStringArrayWithChar:ch outputBlock:^(NSArray *array) {
if (outputBlock) {
if (nil != array) {
NSMutableArray *targetPinyinStringArray = [NSMutableArray arrayWithCapacity:array.count];
for (int i = 0; i < (int) [array count]; i++) {
///to do
}
outputBlock(targetPinyinStringArray);
}
else{
outputBlock(nil);
}
}
}];
}
+ (void)toGwoyeuRomatzyhStringArrayWithChar:(unichar)ch
outputBlock:(OutputArrayBlock)outputBlock
{
[PinyinHelper convertToGwoyeuRomatzyhStringArrayWithChar:ch outputBlock:outputBlock];
}
+ (void)convertToGwoyeuRomatzyhStringArrayWithChar:(unichar)ch
outputBlock:(OutputArrayBlock)outputBlock
{
[PinyinHelper getUnformattedHanyuPinyinStringArrayWithChar:ch outputBlock:^(NSArray *array) {
if (outputBlock) {
if (nil != array) {
NSMutableArray *targetPinyinStringArray = [NSMutableArray arrayWithCapacity:array.count];
for (int i = 0; i < (int) [array count]; i++) {
///to do
}
outputBlock(targetPinyinStringArray);
}
else{
outputBlock(nil);
}
}
}];
}
+ (void)toHanyuPinyinStringWithNSString:(NSString *)str
withHanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)outputFormat
withNSString:(NSString *)seperater
outputBlock:(OutputStringBlock)outputBlock
{
// __block NSMutableString *resultPinyinStrBuf = [[NSMutableString alloc] init];
// for (int i = 0; i < str.length; i++) {
// [PinyinHelper getFirstHanyuPinyinStringWithChar:[str characterAtIndex:i] withHanyuPinyinOutputFormat:outputFormat outputBlock:^(NSString *pinYin) {
// if (nil != pinYin) {
// [resultPinyinStrBuf appendString:pinYin];
// if (i != [str length] - 1) {
// [resultPinyinStrBuf appendString:seperater];
// }
// }
// else {
// [resultPinyinStrBuf appendFormat:@"%C",[str characterAtIndex:i]];
// }
// if (outputBlock) {
// outputBlock(resultPinyinStrBuf);
// }
//
// }];
// }
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
__block NSMutableString *resultPinyinStrBuf = [[NSMutableString alloc] init];
for (int i = 0; i < str.length; i++) {
NSString *mainPinyinStrOfChar = [PinyinHelper getFirstHanyuPinyinStringWithChar:[str characterAtIndex:i] withHanyuPinyinOutputFormat:outputFormat];
if (nil != mainPinyinStrOfChar) {
[resultPinyinStrBuf appendString:mainPinyinStrOfChar];
if (i != [str length] - 1) {
[resultPinyinStrBuf appendString:seperater];
}
}
else {
[resultPinyinStrBuf appendFormat:@"%C",[str characterAtIndex:i]];
}
}
dispatch_async(dispatch_get_main_queue(), ^{
if (outputBlock) {
outputBlock(resultPinyinStrBuf);
}
});
});
}
+ (void)getFirstHanyuPinyinStringWithChar:(unichar)ch
withHanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)outputFormat
outputBlock:(OutputStringBlock)outputBlock
{
[self getFormattedHanyuPinyinStringArrayWithChar:ch withHanyuPinyinOutputFormat:outputFormat outputBlock:^(NSArray *array) {
if (outputBlock) {
if ((nil != array) && ((int) [array count] > 0)) {
outputBlock([array objectAtIndex:0]);
}else {
outputBlock(nil);
}
}
}];
}
/////sync methods
+ (NSArray *)toHanyuPinyinStringArrayWithChar:(unichar)ch {
return [PinyinHelper getUnformattedHanyuPinyinStringArrayWithChar:ch];
}
+ (NSArray *)toHanyuPinyinStringArrayWithChar:(unichar)ch
withHanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)outputFormat {
return [PinyinHelper getFormattedHanyuPinyinStringArrayWithChar:ch withHanyuPinyinOutputFormat:outputFormat];
}
+ (NSArray *)getFormattedHanyuPinyinStringArrayWithChar:(unichar)ch
withHanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)outputFormat {
NSMutableArray *pinyinStrArray =[NSMutableArray arrayWithArray:[PinyinHelper getUnformattedHanyuPinyinStringArrayWithChar:ch]];
if (nil != pinyinStrArray) {
for (int i = 0; i < (int) [pinyinStrArray count]; i++) {
[pinyinStrArray replaceObjectAtIndex:i withObject:[PinyinFormatter formatHanyuPinyinWithNSString:
[pinyinStrArray objectAtIndex:i]withHanyuPinyinOutputFormat:outputFormat]];
}
return pinyinStrArray;
}
else return nil;
}
+ (NSArray *)getUnformattedHanyuPinyinStringArrayWithChar:(unichar)ch {
return [[ChineseToPinyinResource getInstance] getHanyuPinyinStringArrayWithChar:ch];
}
+ (NSArray *)toTongyongPinyinStringArrayWithChar:(unichar)ch {
return [PinyinHelper convertToTargetPinyinStringArrayWithChar:ch withPinyinRomanizationType: TONGYONG_PINYIN];
}
+ (NSArray *)toWadeGilesPinyinStringArrayWithChar:(unichar)ch {
return [PinyinHelper convertToTargetPinyinStringArrayWithChar:ch withPinyinRomanizationType: WADEGILES_PINYIN];
}
+ (NSArray *)toMPS2PinyinStringArrayWithChar:(unichar)ch {
return [PinyinHelper convertToTargetPinyinStringArrayWithChar:ch withPinyinRomanizationType: MPS2_PINYIN];
}
+ (NSArray *)toYalePinyinStringArrayWithChar:(unichar)ch {
return [PinyinHelper convertToTargetPinyinStringArrayWithChar:ch withPinyinRomanizationType: YALE_PINYIN];
}
+ (NSArray *)convertToTargetPinyinStringArrayWithChar:(unichar)ch
withPinyinRomanizationType:(NSString *)targetPinyinSystem {
NSArray *hanyuPinyinStringArray = [PinyinHelper getUnformattedHanyuPinyinStringArrayWithChar:ch];
if (nil != hanyuPinyinStringArray) {
NSMutableArray *targetPinyinStringArray = [NSMutableArray arrayWithCapacity:hanyuPinyinStringArray.count];
for (int i = 0; i < (int) [hanyuPinyinStringArray count]; i++) {
}
return targetPinyinStringArray;
}
else return nil;
}
+ (NSArray *)toGwoyeuRomatzyhStringArrayWithChar:(unichar)ch {
return [PinyinHelper convertToGwoyeuRomatzyhStringArrayWithChar:ch];
}
+ (NSArray *)convertToGwoyeuRomatzyhStringArrayWithChar:(unichar)ch {
NSArray *hanyuPinyinStringArray = [PinyinHelper getUnformattedHanyuPinyinStringArrayWithChar:ch];
if (nil != hanyuPinyinStringArray) {
NSMutableArray *targetPinyinStringArray =[NSMutableArray arrayWithCapacity:hanyuPinyinStringArray.count];
for (int i = 0; i < (int) [hanyuPinyinStringArray count]; i++) {
}
return targetPinyinStringArray;
}
else return nil;
}
+ (NSString *)toHanyuPinyinStringWithNSString:(NSString *)str
withHanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)outputFormat
withNSString:(NSString *)seperater {
NSMutableString *resultPinyinStrBuf = [[NSMutableString alloc] init];
for (int i = 0; i < str.length; i++) {
NSString *mainPinyinStrOfChar = [PinyinHelper getFirstHanyuPinyinStringWithChar:[str characterAtIndex:i] withHanyuPinyinOutputFormat:outputFormat];
if (nil != mainPinyinStrOfChar) {
[resultPinyinStrBuf appendString:mainPinyinStrOfChar];
if (i != [str length] - 1) {
[resultPinyinStrBuf appendString:seperater];
}
}
else {
[resultPinyinStrBuf appendFormat:@"%C",[str characterAtIndex:i]];
}
}
return resultPinyinStrBuf;
}
+ (NSString *)getFirstHanyuPinyinStringWithChar:(unichar)ch
withHanyuPinyinOutputFormat:(HanyuPinyinOutputFormat *)outputFormat {
NSArray *pinyinStrArray = [PinyinHelper getFormattedHanyuPinyinStringArrayWithChar:ch withHanyuPinyinOutputFormat:outputFormat];
if ((nil != pinyinStrArray) && ((int) [pinyinStrArray count] > 0)) {
return [pinyinStrArray objectAtIndex:0];
}
else {
return nil;
}
}
+ (BOOL)isIncludeChineseInString:(NSString*)str{
for (int i=0; i<str.length; i++) {
unichar ch = [str characterAtIndex:i];
if (0x4e00 < ch && ch < 0x9fff) {
return true;
}
}
return false;
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/PinYin4Objc/Classes/PinyinHelper.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 3,168
|
```objective-c
//
//
//
// Created by kimziv on 13-9-14.
//
#ifndef _ChineseToPinyinResource_H_
#define _ChineseToPinyinResource_H_
@class NSArray;
@class NSMutableDictionary;
@interface ChineseToPinyinResource : NSObject {
NSString* _directory;
NSDictionary *_unicodeToHanyuPinyinTable;
}
//@property(nonatomic, strong)NSDictionary *unicodeToHanyuPinyinTable;
- (id)init;
- (void)initializeResource;
- (NSArray *)getHanyuPinyinStringArrayWithChar:(unichar)ch;
- (BOOL)isValidRecordWithNSString:(NSString *)record;
- (NSString *)getHanyuPinyinRecordFromCharWithChar:(unichar)ch;
+ (ChineseToPinyinResource *)getInstance;
@end
#endif // _ChineseToPinyinResource_H_
```
|
/content/code_sandbox/WeChat/ThirdLib/PinYin4Objc/Classes/ChineseToPinyinResource.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 180
|
```objective-c
/*!
@header WMPlayer.h
@abstract Githubpath_to_url
CSDN:path_to_url
@author Created by zhengwenming on 16/1/24
@version 2.0.0 16/1/24 Creation()
*/
#import "Masonry.h"
@import MediaPlayer;
@import AVFoundation;
@import UIKit;
//
typedef NS_ENUM(NSInteger, WMPlayerState) {
WMPlayerStateFailed, //
WMPlayerStateBuffering, //
WMPlayerStatusReadyToPlay, //
WMPlayerStatePlaying, //
WMPlayerStateStopped, //
WMPlayerStateFinished //
};
//
typedef NS_ENUM(NSInteger, CloseBtnStyle){
CloseBtnStylePop, //pop<-
CloseBtnStyleClose //X
};
@class WMPlayer;
@protocol WMPlayerDelegate <NSObject>
@optional
///
//
-(void)wmplayer:(WMPlayer *)wmplayer clickedPlayOrPauseButton:(UIButton *)playOrPauseBtn;
//
-(void)wmplayer:(WMPlayer *)wmplayer clickedCloseButton:(UIButton *)closeBtn;
//
-(void)wmplayer:(WMPlayer *)wmplayer clickedFullScreenButton:(UIButton *)fullScreenBtn;
//WMPlayer
-(void)wmplayer:(WMPlayer *)wmplayer singleTaped:(UITapGestureRecognizer *)singleTap;
//WMPlayer
-(void)wmplayer:(WMPlayer *)wmplayer doubleTaped:(UITapGestureRecognizer *)doubleTap;
///
//
-(void)wmplayerFailedPlay:(WMPlayer *)wmplayer WMPlayerStatus:(WMPlayerState)state;
//
-(void)wmplayerReadyToPlay:(WMPlayer *)wmplayer WMPlayerStatus:(WMPlayerState)state;
//
-(void)wmplayerFinishedPlay:(WMPlayer *)wmplayer;
@end
/**
* .h
*/
@interface WMPlayer : UIView
/**
* player
*/
@property (nonatomic,retain ) AVPlayer *player;
/**
*playerLayer,frame
*/
@property (nonatomic,retain ) AVPlayerLayer *playerLayer;
/** */
@property (nonatomic, weak)id <WMPlayerDelegate> delegate;
/**
*
*/
@property (nonatomic,retain ) UIView *bottomView;
/**
*
*/
@property (nonatomic,retain ) UIView *topView;
/**
* title
*/
@property (nonatomic,strong) UILabel *titleLabel;
/**
*/
@property (nonatomic, assign) WMPlayerState state;
/**
*/
@property (nonatomic, assign) CloseBtnStyle closeBtnStyle;
/**
*
*/
@property (nonatomic, retain) NSTimer *autoDismissTimer;
/**
* BOOL
*/
@property (nonatomic,assign ) BOOL isFullscreen;
/**
*
*/
@property (nonatomic,retain ) UIButton *fullScreenBtn;
/**
*
*/
@property (nonatomic,retain ) UIButton *playOrPauseBtn;
/**
*
*/
@property (nonatomic,retain ) UIButton *closeBtn;
/**
* UILabel
*/
@property (nonatomic,strong) UILabel *loadFailedLabel;
/**
* item
*/
@property (nonatomic, retain) AVPlayerItem *currentItem;
/**
*
*/
@property (nonatomic,strong) UIActivityIndicatorView *loadingView;
/**
* BOOL
*/
//@property (nonatomic,assign ) BOOL isPlaying;
/**
* USRLStringhttp
*/
@property (nonatomic,copy) NSString *URLString;
/**
* time
* @param seekTime
*/
@property (nonatomic, assign) double seekTime;
/**
*
*/
- (void)play;
/**
*
*/
- (void)pause;
/**
*
*
* @return double
*/
- (double)currentTime;
/**
*
*/
- (void )resetWMPlayer;
/**
*
*/
- (NSString *)version;
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/WMPlayer/WMPlayer.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 781
|
```objective-c
//
// YYKit.h
// YYKit <path_to_url
//
// Created by ibireme on 13/3/30.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <Foundation/Foundation.h>
#if __has_include(<YYKit/YYKit.h>)
FOUNDATION_EXPORT double YYKitVersionNumber;
FOUNDATION_EXPORT const unsigned char YYKitVersionString[];
#import <YYKit/YYKitMacro.h>
#import <YYKit/NSObject+YYAdd.h>
#import <YYKit/NSObject+YYAddForKVO.h>
#import <YYKit/NSObject+YYAddForARC.h>
#import <YYKit/NSString+YYAdd.h>
#import <YYKit/NSNumber+YYAdd.h>
#import <YYKit/NSData+YYAdd.h>
#import <YYKit/NSArray+YYAdd.h>
#import <YYKit/NSDictionary+YYAdd.h>
#import <YYKit/NSDate+YYAdd.h>
#import <YYKit/NSNotificationCenter+YYAdd.h>
#import <YYKit/NSKeyedUnarchiver+YYAdd.h>
#import <YYKit/NSTimer+YYAdd.h>
#import <YYKit/NSBundle+YYAdd.h>
#import <YYKit/NSThread+YYAdd.h>
#import <YYKit/UIColor+YYAdd.h>
#import <YYKit/UIImage+YYAdd.h>
#import <YYKit/UIControl+YYAdd.h>
#import <YYKit/UIBarButtonItem+YYAdd.h>
#import <YYKit/UIGestureRecognizer+YYAdd.h>
#import <YYKit/UIView+YYAdd.h>
#import <YYKit/UIScrollView+YYAdd.h>
#import <YYKit/UITableView+YYAdd.h>
#import <YYKit/UITextField+YYAdd.h>
#import <YYKit/UIScreen+YYAdd.h>
#import <YYKit/UIDevice+YYAdd.h>
#import <YYKit/UIApplication+YYAdd.h>
#import <YYKit/UIFont+YYAdd.h>
#import <YYKit/UIBezierPath+YYAdd.h>
#import <YYKit/CALayer+YYAdd.h>
#import <YYKit/YYCGUtilities.h>
#import <YYKit/NSObject+YYModel.h>
#import <YYKit/YYClassInfo.h>
#import <YYKit/YYCache.h>
#import <YYKit/YYMemoryCache.h>
#import <YYKit/YYDiskCache.h>
#import <YYKit/YYKVStorage.h>
#import <YYKit/YYImage.h>
#import <YYKit/YYFrameImage.h>
#import <YYKit/YYSpriteSheetImage.h>
#import <YYKit/YYAnimatedImageView.h>
#import <YYKit/YYImageCoder.h>
#import <YYKit/YYImageCache.h>
#import <YYKit/YYWebImageOperation.h>
#import <YYKit/YYWebImageManager.h>
#import <YYKit/UIImageView+YYWebImage.h>
#import <YYKit/UIButton+YYWebImage.h>
#import <YYKit/MKAnnotationView+YYWebImage.h>
#import <YYKit/CALayer+YYWebImage.h>
#import <YYKit/YYLabel.h>
#import <YYKit/YYTextView.h>
#import <YYKit/YYTextAttribute.h>
#import <YYKit/YYTextArchiver.h>
#import <YYKit/YYTextParser.h>
#import <YYKit/YYTextUtilities.h>
#import <YYKit/YYTextRunDelegate.h>
#import <YYKit/YYTextRubyAnnotation.h>
#import <YYKit/NSAttributedString+YYText.h>
#import <YYKit/NSParagraphStyle+YYText.h>
#import <YYKit/UIPasteboard+YYText.h>
#import <YYKit/YYTextLayout.h>
#import <YYKit/YYTextLine.h>
#import <YYKit/YYTextInput.h>
#import <YYKit/YYTextDebugOption.h>
#import <YYKit/YYTextContainerView.h>
#import <YYKit/YYTextSelectionView.h>
#import <YYKit/YYTextMagnifier.h>
#import <YYKit/YYTextEffectWindow.h>
#import <YYKit/YYTextKeyboardManager.h>
#import <YYKit/YYReachability.h>
#import <YYKit/YYGestureRecognizer.h>
#import <YYKit/YYFileHash.h>
#import <YYKit/YYKeychain.h>
#import <YYKit/YYWeakProxy.h>
#import <YYKit/YYTimer.h>
#import <YYKit/YYTransaction.h>
#import <YYKit/YYAsyncLayer.h>
#import <YYKit/YYSentinel.h>
#import <YYKit/YYDispatchQueuePool.h>
#import <YYKit/YYThreadSafeArray.h>
#import <YYKit/YYThreadSafeDictionary.h>
#else
#import "YYKitMacro.h"
#import "NSObject+YYAdd.h"
#import "NSObject+YYAddForKVO.h"
#import "NSObject+YYAddForARC.h"
#import "NSString+YYAdd.h"
#import "NSNumber+YYAdd.h"
#import "NSData+YYAdd.h"
#import "NSArray+YYAdd.h"
#import "NSDictionary+YYAdd.h"
#import "NSDate+YYAdd.h"
#import "NSNotificationCenter+YYAdd.h"
#import "NSKeyedUnarchiver+YYAdd.h"
#import "NSTimer+YYAdd.h"
#import "NSBundle+YYAdd.h"
#import "NSThread+YYAdd.h"
#import "UIColor+YYAdd.h"
#import "UIImage+YYAdd.h"
#import "UIControl+YYAdd.h"
#import "UIBarButtonItem+YYAdd.h"
#import "UIGestureRecognizer+YYAdd.h"
#import "UIView+YYAdd.h"
#import "UIScrollView+YYAdd.h"
#import "UITableView+YYAdd.h"
#import "UITextField+YYAdd.h"
#import "UIScreen+YYAdd.h"
#import "UIDevice+YYAdd.h"
#import "UIApplication+YYAdd.h"
#import "UIFont+YYAdd.h"
#import "UIBezierPath+YYAdd.h"
#import "CALayer+YYAdd.h"
#import "YYCGUtilities.h"
#import "NSObject+YYModel.h"
#import "YYClassInfo.h"
#import "YYCache.h"
#import "YYMemoryCache.h"
#import "YYDiskCache.h"
#import "YYKVStorage.h"
#import "YYImage.h"
#import "YYFrameImage.h"
#import "YYSpriteSheetImage.h"
#import "YYAnimatedImageView.h"
#import "YYImageCoder.h"
#import "YYImageCache.h"
#import "YYWebImageOperation.h"
#import "YYWebImageManager.h"
#import "UIImageView+YYWebImage.h"
#import "UIButton+YYWebImage.h"
#import "MKAnnotationView+YYWebImage.h"
#import "CALayer+YYWebImage.h"
#import "YYLabel.h"
#import "YYFPSLabel.h"
#import "YYTextView.h"
#import "YYTextAttribute.h"
#import "YYTextArchiver.h"
#import "YYTextParser.h"
#import "YYTextUtilities.h"
#import "YYTextRunDelegate.h"
#import "YYTextRubyAnnotation.h"
#import "NSAttributedString+YYText.h"
#import "NSParagraphStyle+YYText.h"
#import "UIPasteboard+YYText.h"
#import "YYTextLayout.h"
#import "YYTextLine.h"
#import "YYTextInput.h"
#import "YYTextDebugOption.h"
#import "YYTextContainerView.h"
#import "YYTextSelectionView.h"
#import "YYTextMagnifier.h"
#import "YYTextEffectWindow.h"
#import "YYTextKeyboardManager.h"
#import "YYReachability.h"
#import "YYGestureRecognizer.h"
#import "YYFileHash.h"
#import "YYKeychain.h"
#import "YYWeakProxy.h"
#import "YYTimer.h"
#import "YYTransaction.h"
#import "YYAsyncLayer.h"
#import "YYSentinel.h"
#import "YYDispatchQueuePool.h"
#import "YYThreadSafeArray.h"
#import "YYThreadSafeDictionary.h"
#endif
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/YYKit.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,635
|
```objective-c
//
// YYDiskCache.m
// YYKit <path_to_url
//
// Created by ibireme on 15/2/11.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "YYDiskCache.h"
#import "YYKVStorage.h"
#import "NSString+YYAdd.h"
#import "UIDevice+YYAdd.h"
#import <objc/runtime.h>
#import <time.h>
#define Lock() dispatch_semaphore_wait(self->_lock, DISPATCH_TIME_FOREVER)
#define Unlock() dispatch_semaphore_signal(self->_lock)
static const int extended_data_key;
/// Free disk space in bytes.
static int64_t _YYDiskSpaceFree() {
NSError *error = nil;
NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
if (error) return -1;
int64_t space = [[attrs objectForKey:NSFileSystemFreeSize] longLongValue];
if (space < 0) space = -1;
return space;
}
/// weak reference for all instances
static NSMapTable *_globalInstances;
static dispatch_semaphore_t _globalInstancesLock;
static void _YYDiskCacheInitGlobal() {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_globalInstancesLock = dispatch_semaphore_create(1);
_globalInstances = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:0];
});
}
static YYDiskCache *_YYDiskCacheGetGlobal(NSString *path) {
if (path.length == 0) return nil;
_YYDiskCacheInitGlobal();
dispatch_semaphore_wait(_globalInstancesLock, DISPATCH_TIME_FOREVER);
id cache = [_globalInstances objectForKey:path];
dispatch_semaphore_signal(_globalInstancesLock);
return cache;
}
static void _YYDiskCacheSetGlobal(YYDiskCache *cache) {
if (cache.path.length == 0) return;
_YYDiskCacheInitGlobal();
dispatch_semaphore_wait(_globalInstancesLock, DISPATCH_TIME_FOREVER);
[_globalInstances setObject:cache forKey:cache.path];
dispatch_semaphore_signal(_globalInstancesLock);
}
@implementation YYDiskCache {
YYKVStorage *_kv;
dispatch_semaphore_t _lock;
dispatch_queue_t _queue;
}
- (void)_trimRecursively {
__weak typeof(self) _self = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_autoTrimInterval * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
__strong typeof(_self) self = _self;
if (!self) return;
[self _trimInBackground];
[self _trimRecursively];
});
}
- (void)_trimInBackground {
__weak typeof(self) _self = self;
dispatch_async(_queue, ^{
__strong typeof(_self) self = _self;
if (!self) return;
Lock();
[self _trimToCost:self.costLimit];
[self _trimToCount:self.countLimit];
[self _trimToAge:self.ageLimit];
[self _trimToFreeDiskSpace:self.freeDiskSpaceLimit];
Unlock();
});
}
- (void)_trimToCost:(NSUInteger)costLimit {
if (costLimit >= INT_MAX) return;
[_kv removeItemsToFitSize:(int)costLimit];
}
- (void)_trimToCount:(NSUInteger)countLimit {
if (countLimit >= INT_MAX) return;
[_kv removeItemsToFitCount:(int)countLimit];
}
- (void)_trimToAge:(NSTimeInterval)ageLimit {
if (ageLimit <= 0) {
[_kv removeAllItems];
return;
}
long timestamp = time(NULL);
if (timestamp <= ageLimit) return;
long age = timestamp - ageLimit;
if (age >= INT_MAX) return;
[_kv removeItemsEarlierThanTime:(int)age];
}
- (void)_trimToFreeDiskSpace:(NSUInteger)targetFreeDiskSpace {
if (targetFreeDiskSpace == 0) return;
int64_t totalBytes = [_kv getItemsSize];
if (totalBytes <= 0) return;
int64_t diskFreeBytes = _YYDiskSpaceFree();
if (diskFreeBytes < 0) return;
int64_t needTrimBytes = targetFreeDiskSpace - diskFreeBytes;
if (needTrimBytes <= 0) return;
int64_t costLimit = totalBytes - needTrimBytes;
if (costLimit < 0) costLimit = 0;
[self _trimToCost:(int)costLimit];
}
- (NSString *)_filenameForKey:(NSString *)key {
NSString *filename = nil;
if (_customFileNameBlock) filename = _customFileNameBlock(key);
if (!filename) filename = key.md5String;
return filename;
}
- (void)_appWillBeTerminated {
Lock();
_kv = nil;
Unlock();
}
#pragma mark - public
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];
}
- (instancetype)init {
@throw [NSException exceptionWithName:@"YYDiskCache init error" reason:@"YYDiskCache must be initialized with a path. Use 'initWithPath:' or 'initWithPath:inlineThreshold:' instead." userInfo:nil];
return [self initWithPath:@"" inlineThreshold:0];
}
- (instancetype)initWithPath:(NSString *)path {
return [self initWithPath:path inlineThreshold:1024 * 20]; // 20KB
}
- (instancetype)initWithPath:(NSString *)path
inlineThreshold:(NSUInteger)threshold {
self = [super init];
if (!self) return nil;
YYDiskCache *globalCache = _YYDiskCacheGetGlobal(path);
if (globalCache) return globalCache;
YYKVStorageType type;
if (threshold == 0) {
type = YYKVStorageTypeFile;
} else if (threshold == NSUIntegerMax) {
type = YYKVStorageTypeSQLite;
} else {
type = YYKVStorageTypeMixed;
}
YYKVStorage *kv = [[YYKVStorage alloc] initWithPath:path type:type];
if (!kv) return nil;
_kv = kv;
_path = path;
_lock = dispatch_semaphore_create(1);
_queue = dispatch_queue_create("com.ibireme.cache.disk", DISPATCH_QUEUE_CONCURRENT);
_inlineThreshold = threshold;
_countLimit = NSUIntegerMax;
_costLimit = NSUIntegerMax;
_ageLimit = DBL_MAX;
_freeDiskSpaceLimit = 0;
_autoTrimInterval = 60;
[self _trimRecursively];
_YYDiskCacheSetGlobal(self);
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_appWillBeTerminated) name:UIApplicationWillTerminateNotification object:nil];
return self;
}
- (BOOL)containsObjectForKey:(NSString *)key {
if (!key) return NO;
Lock();
BOOL contains = [_kv itemExistsForKey:key];
Unlock();
return contains;
}
- (void)containsObjectForKey:(NSString *)key withBlock:(void(^)(NSString *key, BOOL contains))block {
if (!block) return;
__weak typeof(self) _self = self;
dispatch_async(_queue, ^{
__strong typeof(_self) self = _self;
BOOL contains = [self containsObjectForKey:key];
block(key, contains);
});
}
- (id<NSCoding>)objectForKey:(NSString *)key {
if (!key) return nil;
Lock();
YYKVStorageItem *item = [_kv getItemForKey:key];
Unlock();
if (!item.value) return nil;
id object = nil;
if (_customUnarchiveBlock) {
object = _customUnarchiveBlock(item.value);
} else {
@try {
object = [NSKeyedUnarchiver unarchiveObjectWithData:item.value];
}
@catch (NSException *exception) {
// nothing to do...
}
}
if (object && item.extendedData) {
[YYDiskCache setExtendedData:item.extendedData toObject:object];
}
return object;
}
- (void)objectForKey:(NSString *)key withBlock:(void(^)(NSString *key, id<NSCoding> object))block {
if (!block) return;
__weak typeof(self) _self = self;
dispatch_async(_queue, ^{
__strong typeof(_self) self = _self;
id<NSCoding> object = [self objectForKey:key];
block(key, object);
});
}
- (void)setObject:(id<NSCoding>)object forKey:(NSString *)key {
if (!key) return;
if (!object) {
[self removeObjectForKey:key];
return;
}
NSData *extendedData = [YYDiskCache getExtendedDataFromObject:object];
NSData *value = nil;
if (_customArchiveBlock) {
value = _customArchiveBlock(object);
} else {
@try {
value = [NSKeyedArchiver archivedDataWithRootObject:object];
}
@catch (NSException *exception) {
// nothing to do...
}
}
if (!value) return;
NSString *filename = nil;
if (_kv.type != YYKVStorageTypeSQLite) {
if (value.length > _inlineThreshold) {
filename = [self _filenameForKey:key];
}
}
Lock();
[_kv saveItemWithKey:key value:value filename:filename extendedData:extendedData];
Unlock();
}
- (void)setObject:(id<NSCoding>)object forKey:(NSString *)key withBlock:(void(^)(void))block {
__weak typeof(self) _self = self;
dispatch_async(_queue, ^{
__strong typeof(_self) self = _self;
[self setObject:object forKey:key];
if (block) block();
});
}
- (void)removeObjectForKey:(NSString *)key {
if (!key) return;
Lock();
[_kv removeItemForKey:key];
Unlock();
}
- (void)removeObjectForKey:(NSString *)key withBlock:(void(^)(NSString *key))block {
__weak typeof(self) _self = self;
dispatch_async(_queue, ^{
__strong typeof(_self) self = _self;
[self removeObjectForKey:key];
if (block) block(key);
});
}
- (void)removeAllObjects {
Lock();
[_kv removeAllItems];
Unlock();
}
- (void)removeAllObjectsWithBlock:(void(^)(void))block {
__weak typeof(self) _self = self;
dispatch_async(_queue, ^{
__strong typeof(_self) self = _self;
[self removeAllObjects];
if (block) block();
});
}
- (void)removeAllObjectsWithProgressBlock:(void(^)(int removedCount, int totalCount))progress
endBlock:(void(^)(BOOL error))end {
__weak typeof(self) _self = self;
dispatch_async(_queue, ^{
__strong typeof(_self) self = _self;
if (!self) {
if (end) end(YES);
return;
}
Lock();
[_kv removeAllItemsWithProgressBlock:progress endBlock:end];
Unlock();
});
}
- (NSInteger)totalCount {
Lock();
int count = [_kv getItemsCount];
Unlock();
return count;
}
- (void)totalCountWithBlock:(void(^)(NSInteger totalCount))block {
if (!block) return;
__weak typeof(self) _self = self;
dispatch_async(_queue, ^{
__strong typeof(_self) self = _self;
NSInteger totalCount = [self totalCount];
block(totalCount);
});
}
- (NSInteger)totalCost {
Lock();
int count = [_kv getItemsSize];
Unlock();
return count;
}
- (void)totalCostWithBlock:(void(^)(NSInteger totalCost))block {
if (!block) return;
__weak typeof(self) _self = self;
dispatch_async(_queue, ^{
__strong typeof(_self) self = _self;
NSInteger totalCost = [self totalCost];
block(totalCost);
});
}
- (void)trimToCount:(NSUInteger)count {
Lock();
[self _trimToCount:count];
Unlock();
}
- (void)trimToCount:(NSUInteger)count withBlock:(void(^)(void))block {
__weak typeof(self) _self = self;
dispatch_async(_queue, ^{
__strong typeof(_self) self = _self;
[self trimToCount:count];
if (block) block();
});
}
- (void)trimToCost:(NSUInteger)cost {
Lock();
[self _trimToCost:cost];
Unlock();
}
- (void)trimToCost:(NSUInteger)cost withBlock:(void(^)(void))block {
__weak typeof(self) _self = self;
dispatch_async(_queue, ^{
__strong typeof(_self) self = _self;
[self trimToCost:cost];
if (block) block();
});
}
- (void)trimToAge:(NSTimeInterval)age {
Lock();
[self _trimToAge:age];
Unlock();
}
- (void)trimToAge:(NSTimeInterval)age withBlock:(void(^)(void))block {
__weak typeof(self) _self = self;
dispatch_async(_queue, ^{
__strong typeof(_self) self = _self;
[self trimToAge:age];
if (block) block();
});
}
+ (NSData *)getExtendedDataFromObject:(id)object {
if (!object) return nil;
return (NSData *)objc_getAssociatedObject(object, &extended_data_key);
}
+ (void)setExtendedData:(NSData *)extendedData toObject:(id)object {
if (!object) return;
objc_setAssociatedObject(object, &extended_data_key, extendedData, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSString *)description {
if (_name) return [NSString stringWithFormat:@"<%@: %p> (%@:%@)", self.class, self, _name, _path];
else return [NSString stringWithFormat:@"<%@: %p> (%@)", self.class, self, _path];
}
- (BOOL)errorLogsEnabled {
Lock();
BOOL enabled = _kv.errorLogsEnabled;
Unlock();
return enabled;
}
- (void)setErrorLogsEnabled:(BOOL)errorLogsEnabled {
Lock();
_kv.errorLogsEnabled = errorLogsEnabled;
Unlock();
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Cache/YYDiskCache.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 3,155
|
```objective-c
//
// YYCache.h
// YYKit <path_to_url
//
// Created by ibireme on 15/2/13.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <Foundation/Foundation.h>
@class YYMemoryCache, YYDiskCache;
NS_ASSUME_NONNULL_BEGIN
/**
`YYCache` is a thread safe key-value cache.
It use `YYMemoryCache` to store objects in a small and fast memory cache,
and use `YYDiskCache` to persisting objects to a large and slow disk cache.
See `YYMemoryCache` and `YYDiskCache` for more information.
*/
@interface YYCache : NSObject
/** The name of the cache, readonly. */
@property (copy, readonly) NSString *name;
/** The underlying memory cache. see `YYMemoryCache` for more information.*/
@property (strong, readonly) YYMemoryCache *memoryCache;
/** The underlying disk cache. see `YYDiskCache` for more information.*/
@property (strong, readonly) YYDiskCache *diskCache;
/**
Create a new instance with the specified name.
Multiple instances with the same name will make the cache unstable.
@param name The name of the cache. It will create a dictionary with the name in
the app's caches dictionary for disk cache. Once initialized you should not
read and write to this directory.
@result A new cache object, or nil if an error occurs.
*/
- (nullable instancetype)initWithName:(NSString *)name;
/**
Create a new instance with the specified path.
Multiple instances with the same name will make the cache unstable.
@param path Full path of a directory in which the cache will write data.
Once initialized you should not read and write to this directory.
@result A new cache object, or nil if an error occurs.
*/
- (nullable instancetype)initWithPath:(NSString *)path NS_DESIGNATED_INITIALIZER;
/**
Convenience Initializers
Create a new instance with the specified name.
Multiple instances with the same name will make the cache unstable.
@param name The name of the cache. It will create a dictionary with the name in
the app's caches dictionary for disk cache. Once initialized you should not
read and write to this directory.
@result A new cache object, or nil if an error occurs.
*/
+ (nullable instancetype)cacheWithName:(NSString *)name;
/**
Convenience Initializers
Create a new instance with the specified path.
Multiple instances with the same name will make the cache unstable.
@param path Full path of a directory in which the cache will write data.
Once initialized you should not read and write to this directory.
@result A new cache object, or nil if an error occurs.
*/
+ (nullable instancetype)cacheWithPath:(NSString *)path;
- (instancetype)init UNAVAILABLE_ATTRIBUTE;
+ (instancetype)new UNAVAILABLE_ATTRIBUTE;
#pragma mark - Access Methods
///=============================================================================
/// @name Access Methods
///=============================================================================
/**
Returns a boolean value that indicates whether a given key is in cache.
This method may blocks the calling thread until file read finished.
@param key A string identifying the value. If nil, just return NO.
@return Whether the key is in cache.
*/
- (BOOL)containsObjectForKey:(NSString *)key;
/**
Returns a boolean value with the block that indicates whether a given key is in cache.
This method returns immediately and invoke the passed block in background queue
when the operation finished.
@param key A string identifying the value. If nil, just return NO.
@param block A block which will be invoked in background queue when finished.
*/
- (void)containsObjectForKey:(NSString *)key withBlock:(nullable void(^)(NSString *key, BOOL contains))block;
/**
Returns the value associated with a given key.
This method may blocks the calling thread until file read finished.
@param key A string identifying the value. If nil, just return nil.
@return The value associated with key, or nil if no value is associated with key.
*/
- (nullable id<NSCoding>)objectForKey:(NSString *)key;
/**
Returns the value associated with a given key.
This method returns immediately and invoke the passed block in background queue
when the operation finished.
@param key A string identifying the value. If nil, just return nil.
@param block A block which will be invoked in background queue when finished.
*/
- (void)objectForKey:(NSString *)key withBlock:(nullable void(^)(NSString *key, id<NSCoding> object))block;
/**
Sets the value of the specified key in the cache.
This method may blocks the calling thread until file write finished.
@param object The object to be stored in the cache. If nil, it calls `removeObjectForKey:`.
@param key The key with which to associate the value. If nil, this method has no effect.
*/
- (void)setObject:(nullable id<NSCoding>)object forKey:(NSString *)key;
/**
Sets the value of the specified key in the cache.
This method returns immediately and invoke the passed block in background queue
when the operation finished.
@param object The object to be stored in the cache. If nil, it calls `removeObjectForKey:`.
@param block A block which will be invoked in background queue when finished.
*/
- (void)setObject:(nullable id<NSCoding>)object forKey:(NSString *)key withBlock:(nullable void(^)(void))block;
/**
Removes the value of the specified key in the cache.
This method may blocks the calling thread until file delete finished.
@param key The key identifying the value to be removed. If nil, this method has no effect.
*/
- (void)removeObjectForKey:(NSString *)key;
/**
Removes the value of the specified key in the cache.
This method returns immediately and invoke the passed block in background queue
when the operation finished.
@param key The key identifying the value to be removed. If nil, this method has no effect.
@param block A block which will be invoked in background queue when finished.
*/
- (void)removeObjectForKey:(NSString *)key withBlock:(nullable void(^)(NSString *key))block;
/**
Empties the cache.
This method may blocks the calling thread until file delete finished.
*/
- (void)removeAllObjects;
/**
Empties the cache.
This method returns immediately and invoke the passed block in background queue
when the operation finished.
@param block A block which will be invoked in background queue when finished.
*/
- (void)removeAllObjectsWithBlock:(void(^)(void))block;
/**
Empties the cache with block.
This method returns immediately and executes the clear operation with block in background.
@warning You should not send message to this instance in these blocks.
@param progress This block will be invoked during removing, pass nil to ignore.
@param end This block will be invoked at the end, pass nil to ignore.
*/
- (void)removeAllObjectsWithProgressBlock:(nullable void(^)(int removedCount, int totalCount))progress
endBlock:(nullable void(^)(BOOL error))end;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Cache/YYCache.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,504
|
```objective-c
/*!
@header WMPlayer.m
@abstract Githubpath_to_url
CSDN:path_to_url
@author Created by zhengwenming on 16/1/24
@version 2.0.0 16/1/24 Creation()
*/
#import "WMPlayer.h"
#define WMPlayerSrcName(file) [@"WMPlayer.bundle" stringByAppendingPathComponent:file]
#define WMPlayerFrameworkSrcName(file) [@"Frameworks/WMPlayer.framework/WMPlayer.bundle" stringByAppendingPathComponent:file]
#define kHalfWidth self.frame.size.width * 0.5
#define kHalfHeight self.frame.size.height * 0.5
static void *PlayViewCMTimeValue = &PlayViewCMTimeValue;
static void *PlayViewStatusObservationContext = &PlayViewStatusObservationContext;
@interface WMPlayer () <UIGestureRecognizerDelegate>
@property (nonatomic,assign)CGPoint firstPoint;
@property (nonatomic,assign)CGPoint secondPoint;
@property (nonatomic, strong)NSDateFormatter *dateFormatter;
//
@property (nonatomic ,strong) id playbackTimeObserver;
//
@property (nonatomic, strong) UITapGestureRecognizer *tap;
@property (nonatomic, assign) CGPoint originalPoint;
@property (nonatomic, assign) BOOL isDragingSlider;//
/**
* UILabel
*/
@property (nonatomic,strong) UILabel *leftTimeLabel;
@property (nonatomic,strong) UILabel *rightTimeLabel;
/**
*
*/
@property (nonatomic,strong) UISlider *lightSlider;
@property (nonatomic,strong) UISlider *progressSlider;
@property (nonatomic,strong) UISlider *volumeSlider;
@property (nonatomic,strong) UIProgressView *loadingProgress;
@end
@implementation WMPlayer{
UISlider *systemSlider;
UITapGestureRecognizer* singleTap;
}
/**
* alloc init
*/
- (instancetype)init{
self = [super init];
if (self){
[self initWMPlayer];
}
return self;
}
/**
* storyboardxib
*/
- (void)awakeFromNib
{
[self initWMPlayer];
}
/**
* initWithFrame
*/
-(instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
[self initWMPlayer];
}
return self;
}
/**
* WMPlayerkvo
*/
-(void)initWMPlayer{
self.seekTime = 0.00;
self.backgroundColor = [UIColor blackColor];
//
self.loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
// UIActivityIndicatorViewStyleWhiteLarge 3737
// UIActivityIndicatorViewStyleWhite 2222
[self addSubview:self.loadingView];
[self.loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(self);
}];
[self.loadingView startAnimating];
//topView
self.topView = [[UIView alloc]init];
self.topView.backgroundColor = [UIColor colorWithWhite:0.4 alpha:0.4];
[self addSubview:self.topView];
//autoLayout topView
[self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self).with.offset(0);
make.right.equalTo(self).with.offset(0);
make.height.mas_equalTo(40);
make.top.equalTo(self).with.offset(0);
}];
//bottomView
self.bottomView = [[UIView alloc]init];
self.bottomView.backgroundColor = [UIColor colorWithWhite:0.4 alpha:0.4];
[self addSubview:self.bottomView];
//autoLayout bottomView
[self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self).with.offset(0);
make.right.equalTo(self).with.offset(0);
make.height.mas_equalTo(40);
make.bottom.equalTo(self).with.offset(0);
}];
[self setAutoresizesSubviews:NO];
//_playOrPauseBtn
self.playOrPauseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
self.playOrPauseBtn.showsTouchWhenHighlighted = YES;
[self.playOrPauseBtn addTarget:self action:@selector(PlayOrPause:) forControlEvents:UIControlEventTouchUpInside];
[self.playOrPauseBtn setImage:[UIImage imageNamed:WMPlayerSrcName(@"pause")] ?: [UIImage imageNamed:WMPlayerFrameworkSrcName(@"pause")] forState:UIControlStateNormal];
[self.playOrPauseBtn setImage:[UIImage imageNamed:WMPlayerSrcName(@"play")] ?: [UIImage imageNamed:WMPlayerFrameworkSrcName(@"play")] forState:UIControlStateSelected];
[self.bottomView addSubview:self.playOrPauseBtn];
//autoLayout _playOrPauseBtn
[self.playOrPauseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.bottomView).with.offset(0);
make.height.mas_equalTo(40);
make.bottom.equalTo(self.bottomView).with.offset(0);
make.width.mas_equalTo(40);
}];
//
self.lightSlider = [[UISlider alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
self.lightSlider.hidden = YES;
self.lightSlider.minimumValue = 0;
self.lightSlider.maximumValue = 1;
// ,0~1
self.lightSlider.value = [UIScreen mainScreen].brightness;
// [self.lightSlider addTarget:self action:@selector(updateLightValue:) forControlEvents:UIControlEventValueChanged];
[self addSubview:self.lightSlider];
MPVolumeView *volumeView = [[MPVolumeView alloc]init];
[self addSubview:volumeView];
volumeView.frame = CGRectMake(-1000, -100, 100, 100);
[volumeView sizeToFit];
systemSlider = [[UISlider alloc]init];
systemSlider.backgroundColor = [UIColor clearColor];
for (UIControl *view in volumeView.subviews) {
if ([view.superclass isSubclassOfClass:[UISlider class]]) {
systemSlider = (UISlider *)view;
}
}
systemSlider.autoresizesSubviews = NO;
systemSlider.autoresizingMask = UIViewAutoresizingNone;
[self addSubview:systemSlider];
// systemSlider.hidden = YES;
self.volumeSlider = [[UISlider alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
self.volumeSlider.tag = 1000;
self.volumeSlider.hidden = YES;
self.volumeSlider.minimumValue = systemSlider.minimumValue;
self.volumeSlider.maximumValue = systemSlider.maximumValue;
self.volumeSlider.value = systemSlider.value;
[self.volumeSlider addTarget:self action:@selector(updateSystemVolumeValue:) forControlEvents:UIControlEventValueChanged];
[self addSubview:self.volumeSlider];
//slider
self.progressSlider = [[UISlider alloc]init];
self.progressSlider.minimumValue = 0.0;
[self.progressSlider setThumbImage:[UIImage imageNamed:WMPlayerSrcName(@"dot")] ?: [UIImage imageNamed:WMPlayerFrameworkSrcName(@"dot")] forState:UIControlStateNormal];
self.progressSlider.minimumTrackTintColor = [UIColor greenColor];
self.progressSlider.maximumTrackTintColor = [UIColor clearColor];
self.progressSlider.value = 0.0;//
//
[self.progressSlider addTarget:self action:@selector(stratDragSlide:) forControlEvents:UIControlEventValueChanged];
//
[self.progressSlider addTarget:self action:@selector(updateProgress:) forControlEvents:UIControlEventTouchUpInside];
//
self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionTapGesture:)];
self.tap.delegate = self;
[self.progressSlider addGestureRecognizer:self.tap];
[self.bottomView addSubview:self.progressSlider];
self.progressSlider.backgroundColor = [UIColor clearColor];
//autoLayout slider
[self.progressSlider mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.bottomView).with.offset(45);
make.right.equalTo(self.bottomView).with.offset(-45);
make.center.equalTo(self.bottomView);
}];
self.loadingProgress = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
self.loadingProgress.progressTintColor = [UIColor clearColor];
self.loadingProgress.trackTintColor = [UIColor lightGrayColor];
[self.bottomView addSubview:self.loadingProgress];
[self.loadingProgress setProgress:0.0 animated:NO];
[self.loadingProgress mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.progressSlider);
make.right.equalTo(self.progressSlider);
make.center.equalTo(self.progressSlider).with.offset(0.7);
}];
[self.bottomView sendSubviewToBack:self.loadingProgress];
//_fullScreenBtn
self.fullScreenBtn = [UIButton buttonWithType:UIButtonTypeCustom];
self.fullScreenBtn.showsTouchWhenHighlighted = YES;
[self.fullScreenBtn addTarget:self action:@selector(fullScreenAction:) forControlEvents:UIControlEventTouchUpInside];
[self.fullScreenBtn setImage:[UIImage imageNamed:WMPlayerSrcName(@"fullscreen")] ?: [UIImage imageNamed:WMPlayerFrameworkSrcName(@"fullscreen")] forState:UIControlStateNormal];
[self.fullScreenBtn setImage:[UIImage imageNamed:WMPlayerSrcName(@"nonfullscreen")] ?: [UIImage imageNamed:WMPlayerFrameworkSrcName(@"nonfullscreen")] forState:UIControlStateSelected];
[self.bottomView addSubview:self.fullScreenBtn];
//autoLayout fullScreenBtn
[self.fullScreenBtn mas_makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(self.bottomView).with.offset(0);
make.height.mas_equalTo(40);
make.bottom.equalTo(self.bottomView).with.offset(0);
make.width.mas_equalTo(40);
}];
//leftTimeLabel
self.leftTimeLabel = [[UILabel alloc]init];
self.leftTimeLabel.textAlignment = NSTextAlignmentLeft;
self.leftTimeLabel.textColor = [UIColor whiteColor];
self.leftTimeLabel.backgroundColor = [UIColor clearColor];
self.leftTimeLabel.font = [UIFont systemFontOfSize:11];
[self.bottomView addSubview:self.leftTimeLabel];
//autoLayout timeLabel
[self.leftTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.bottomView).with.offset(45);
make.right.equalTo(self.bottomView).with.offset(-45);
make.height.mas_equalTo(20);
make.bottom.equalTo(self.bottomView).with.offset(0);
}];
//rightTimeLabel
self.rightTimeLabel = [[UILabel alloc]init];
self.rightTimeLabel.textAlignment = NSTextAlignmentRight;
self.rightTimeLabel.textColor = [UIColor whiteColor];
self.rightTimeLabel.backgroundColor = [UIColor clearColor];
self.rightTimeLabel.font = [UIFont systemFontOfSize:11];
[self.bottomView addSubview:self.rightTimeLabel];
//autoLayout timeLabel
[self.rightTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.bottomView).with.offset(45);
make.right.equalTo(self.bottomView).with.offset(-45);
make.height.mas_equalTo(20);
make.bottom.equalTo(self.bottomView).with.offset(0);
}];
//_closeBtn
_closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
_closeBtn.showsTouchWhenHighlighted = YES;
[_closeBtn addTarget:self action:@selector(colseTheVideo:) forControlEvents:UIControlEventTouchUpInside];
[self.topView addSubview:_closeBtn];
//autoLayout _closeBtn
[self.closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.topView).with.offset(5);
make.height.mas_equalTo(30);
make.top.equalTo(self.topView).with.offset(5);
make.width.mas_equalTo(30);
}];
//titleLabel
self.titleLabel = [[UILabel alloc]init];
self.titleLabel.textAlignment = NSTextAlignmentCenter;
self.titleLabel.textColor = [UIColor whiteColor];
self.titleLabel.backgroundColor = [UIColor clearColor];
self.titleLabel.font = [UIFont systemFontOfSize:17.0];
[self.topView addSubview:self.titleLabel];
//autoLayout titleLabel
[self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.topView).with.offset(45);
make.right.equalTo(self.topView).with.offset(-45);
make.center.equalTo(self.topView);
make.top.equalTo(self.topView).with.offset(0);
}];
[self bringSubviewToFront:self.loadingView];
[self bringSubviewToFront:self.bottomView];
// Recognizer
singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
singleTap.numberOfTapsRequired = 1; //
singleTap.numberOfTouchesRequired = 1;
[self addGestureRecognizer:singleTap];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appwillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
}
#pragma mark
#pragma mark lazy label
-(UILabel *)loadFailedLabel{
if (_loadFailedLabel==nil) {
_loadFailedLabel = [[UILabel alloc]init];
_loadFailedLabel.textColor = [UIColor whiteColor];
_loadFailedLabel.textAlignment = NSTextAlignmentCenter;
_loadFailedLabel.text = @"";
_loadFailedLabel.hidden = YES;
[self addSubview:_loadFailedLabel];
[_loadFailedLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(self);
make.width.equalTo(self);
make.height.equalTo(@30);
}];
}
return _loadFailedLabel;
}
#pragma mark
#pragma mark
- (void)appDidEnterBackground:(NSNotification*)note
{
if (self.playOrPauseBtn.isSelected==NO) {//
NSArray *tracks = [self.currentItem tracks];
for (AVPlayerItemTrack *playerItemTrack in tracks) {
if ([playerItemTrack.assetTrack hasMediaCharacteristic:AVMediaCharacteristicVisual]) {
playerItemTrack.enabled = YES;
}
}
self.playerLayer.player = nil;
[self.player play];
self.state = WMPlayerStatePlaying;
}else{
self.state = WMPlayerStateStopped;
}
}
#pragma mark
#pragma mark
- (void)appWillEnterForeground:(NSNotification*)note
{
if (self.playOrPauseBtn.isSelected==NO) {//
NSArray *tracks = [self.currentItem tracks];
for (AVPlayerItemTrack *playerItemTrack in tracks) {
if ([playerItemTrack.assetTrack hasMediaCharacteristic:AVMediaCharacteristicVisual]) {
playerItemTrack.enabled = YES;
}
}
self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
self.playerLayer.frame = self.bounds;
self.playerLayer.videoGravity = AVLayerVideoGravityResize;
[self.layer insertSublayer:_playerLayer atIndex:0];
[self.player play];
self.state = WMPlayerStatePlaying;
}else{
self.state = WMPlayerStateStopped;
}
}
#pragma mark
#pragma mark appwillResignActive
- (void)appwillResignActive:(NSNotification *)note
{
NSLog(@"appwillResignActive");
}
- (void)appBecomeActive:(NSNotification *)note
{
NSLog(@"appBecomeActive");
}
//
- (void)actionTapGesture:(UITapGestureRecognizer *)sender {
CGPoint touchLocation = [sender locationInView:self.progressSlider];
CGFloat value = (self.progressSlider.maximumValue - self.progressSlider.minimumValue) * (touchLocation.x/self.progressSlider.frame.size.width);
[self.progressSlider setValue:value animated:YES];
[self.player seekToTime:CMTimeMakeWithSeconds(self.progressSlider.value, self.currentItem.currentTime.timescale)];
if (self.player.rate != 1.f) {
if ([self currentTime] == [self duration])
[self setCurrentTime:0.f];
self.playOrPauseBtn.selected = NO;
[self.player play];
}
}
- (void)updateSystemVolumeValue:(UISlider *)slider{
systemSlider.value = slider.value;
}
#pragma mark
#pragma mark - layoutSubviews
-(void)layoutSubviews{
[super layoutSubviews];
self.playerLayer.frame = self.bounds;
}
#pragma mark
#pragma mark - func
-(void)fullScreenAction:(UIButton *)sender{
sender.selected = !sender.selected;
if (self.delegate&&[self.delegate respondsToSelector:@selector(wmplayer:clickedFullScreenButton:)]) {
[self.delegate wmplayer:self clickedFullScreenButton:sender];
}
}
#pragma mark
#pragma mark - func
-(void)colseTheVideo:(UIButton *)sender{
if (self.delegate&&[self.delegate respondsToSelector:@selector(wmplayer:clickedCloseButton:)]) {
[self.delegate wmplayer:self clickedCloseButton:sender];
}
}
///
- (double)duration{
AVPlayerItem *playerItem = self.player.currentItem;
if (playerItem.status == AVPlayerItemStatusReadyToPlay){
return CMTimeGetSeconds([[playerItem asset] duration]);
}
else{
return 0.f;
}
}
///
- (double)currentTime{
if (self.player) {
return CMTimeGetSeconds([self.player currentTime]);
}else{
return 0.0;
}
}
- (void)setCurrentTime:(double)time{
dispatch_async(dispatch_get_main_queue(), ^{
[self.player seekToTime:CMTimeMakeWithSeconds(time, self.currentItem.currentTime.timescale)];
});
}
#pragma mark
#pragma mark - PlayOrPause
- (void)PlayOrPause:(UIButton *)sender{
if (self.player.rate != 1.f) {
if ([self currentTime] == [self duration])
[self setCurrentTime:0.f];
sender.selected = NO;
[self.player play];
} else {
sender.selected = YES;
[self.player pause];
}
if ([self.delegate respondsToSelector:@selector(wmplayer:clickedPlayOrPauseButton:)]) {
[self.delegate wmplayer:self clickedPlayOrPauseButton:sender];
}
}
///
-(void)play{
[self PlayOrPause:self.playOrPauseBtn];
}
///
-(void)pause{
[self PlayOrPause:self.playOrPauseBtn];
}
#pragma mark
#pragma mark -
- (void)handleSingleTap:(UITapGestureRecognizer *)sender{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(autoDismissBottomView:) object:nil];
if (self.delegate&&[self.delegate respondsToSelector:@selector(wmplayer:singleTaped:)]) {
[self.delegate wmplayer:self singleTaped:sender];
}
[self.autoDismissTimer invalidate];
self.autoDismissTimer = nil;
self.autoDismissTimer = [NSTimer timerWithTimeInterval:5.0 target:self selector:@selector(autoDismissBottomView:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.autoDismissTimer forMode:NSDefaultRunLoopMode];
[UIView animateWithDuration:0.5 animations:^{
if (self.bottomView.alpha == 0.0) {
self.bottomView.alpha = 1.0;
self.closeBtn.alpha = 1.0;
self.topView.alpha = 1.0;
}else{
self.bottomView.alpha = 0.0;
self.closeBtn.alpha = 0.0;
self.topView.alpha = 0.0;
}
} completion:^(BOOL finish){
}];
}
#pragma mark
#pragma mark -
- (void)handleDoubleTap:(UITapGestureRecognizer *)doubleTap{
if (self.delegate&&[self.delegate respondsToSelector:@selector(wmplayer:doubleTaped:)]) {
[self.delegate wmplayer:self doubleTaped:doubleTap];
}
if (self.player.rate != 1.f) {
if ([self currentTime] == self.duration)
[self setCurrentTime:0.f];
[self.player play];
self.playOrPauseBtn.selected = NO;
} else {
[self.player pause];
self.playOrPauseBtn.selected = YES;
}
[UIView animateWithDuration:0.5 animations:^{
self.bottomView.alpha = 1.0;
self.topView.alpha = 1.0;
self.closeBtn.alpha = 1.0;
} completion:^(BOOL finish){
}];
}
-(void)setCurrentItem:(AVPlayerItem *)currentItem{
if (_currentItem==currentItem) {
return;
}
if (_currentItem) {
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:_currentItem];
[_currentItem removeObserver:self forKeyPath:@"status"];
[_currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
[_currentItem removeObserver:self forKeyPath:@"playbackBufferEmpty"];
[_currentItem removeObserver:self forKeyPath:@"playbackLikelyToKeepUp"];
_currentItem = nil;
}
_currentItem = currentItem;
if (_currentItem) {
[_currentItem addObserver:self
forKeyPath:@"status"
options:NSKeyValueObservingOptionNew
context:PlayViewStatusObservationContext];
[_currentItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:PlayViewStatusObservationContext];
//
[_currentItem addObserver:self forKeyPath:@"playbackBufferEmpty" options: NSKeyValueObservingOptionNew context:PlayViewStatusObservationContext];
//
[_currentItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options: NSKeyValueObservingOptionNew context:PlayViewStatusObservationContext];
[self.player replaceCurrentItemWithPlayerItem:_currentItem];
//
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:_currentItem];
}
}
/**
* URLStringsetter
*/
- (void)setURLString:(NSString *)URLString{
_URLString = URLString;
//player
self.currentItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:URLString]];
self.player = [AVPlayer playerWithPlayerItem:_currentItem];
self.player.usesExternalPlaybackWhileExternalScreenIsActive=YES;
//AVPlayerLayer
self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
self.playerLayer.frame = self.layer.bounds;
//WMPlayerAVLayerVideoGravityResizeAspect
self.playerLayer.videoGravity = AVLayerVideoGravityResize;
[self.layer insertSublayer:_playerLayer atIndex:0];
self.state = WMPlayerStateBuffering;
if (self.closeBtnStyle==CloseBtnStylePop) {
[_closeBtn setImage:[UIImage imageNamed:WMPlayerSrcName(@"play_back.png")] ?: [UIImage imageNamed:WMPlayerFrameworkSrcName(@"play_back.png")] forState:UIControlStateNormal];
[_closeBtn setImage:[UIImage imageNamed:WMPlayerSrcName(@"play_back.png")] ?: [UIImage imageNamed:WMPlayerFrameworkSrcName(@"play_back.png")] forState:UIControlStateSelected];
}else{
[_closeBtn setImage:[UIImage imageNamed:WMPlayerSrcName(@"close")] ?: [UIImage imageNamed:WMPlayerFrameworkSrcName(@"close")] forState:UIControlStateNormal];
[_closeBtn setImage:[UIImage imageNamed:WMPlayerSrcName(@"close")] ?: [UIImage imageNamed:WMPlayerFrameworkSrcName(@"close")] forState:UIControlStateSelected];
}
}
/**
*
* @param state WMPlayerState
*/
- (void)setState:(WMPlayerState)state
{
_state = state;
//
if (state == WMPlayerStateBuffering) {
[self.loadingView startAnimating];
}else if(state == WMPlayerStatePlaying){
[self.loadingView stopAnimating];//
}else if(state == WMPlayerStatusReadyToPlay){
[self.loadingView stopAnimating];//
}
else{
[self.loadingView stopAnimating];//
}
}
/**
*
*/
- (UIImage *)buttonImageFromColor:(UIColor *)color{
CGRect rect = self.bounds;
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext(); return img;
}
- (void)moviePlayDidEnd:(NSNotification *)notification {
self.state = WMPlayerStateFinished;
if (self.delegate&&[self.delegate respondsToSelector:@selector(wmplayerFinishedPlay:)]) {
[self.delegate wmplayerFinishedPlay:self];
}
[self.player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
[self.progressSlider setValue:0.0 animated:YES];
self.playOrPauseBtn.selected = YES;
}];
[UIView animateWithDuration:0.5 animations:^{
self.bottomView.alpha = 1.0;
self.topView.alpha = 1.0;
} completion:^(BOOL finish){
}];
}
#pragma mark
#pragma mark--sidle
- (void)stratDragSlide:(UISlider *)slider{
self.isDragingSlider = YES;
}
#pragma mark
#pragma mark -
- (void)updateProgress:(UISlider *)slider{
self.isDragingSlider = NO;
[self.player seekToTime:CMTimeMakeWithSeconds(slider.value, _currentItem.currentTime.timescale)];
}
#pragma mark
#pragma mark KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
/* AVPlayerItem "status" property value observer. */
if (context == PlayViewStatusObservationContext)
{
if ([keyPath isEqualToString:@"status"]) {
AVPlayerStatus status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
switch (status)
{
/* Indicates that the status of the player is not yet known because
it has not tried to load new media resources for playback */
case AVPlayerStatusUnknown:
{
[self.loadingProgress setProgress:0.0 animated:NO];
self.state = WMPlayerStateBuffering;
[self.loadingView startAnimating];
}
break;
case AVPlayerStatusReadyToPlay:
{
self.state = WMPlayerStatusReadyToPlay;
// Recognizer
UITapGestureRecognizer* doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
doubleTap.numberOfTapsRequired = 2; //
[singleTap requireGestureRecognizerToFail:doubleTap];//
[self addGestureRecognizer:doubleTap];
/* Once the AVPlayerItem becomes ready to play, i.e.
[playerItem status] == AVPlayerItemStatusReadyToPlay,
its duration can be fetched from the item. */
if (CMTimeGetSeconds(_currentItem.duration)) {
double _x = CMTimeGetSeconds(_currentItem.duration);
if (!isnan(_x)) {
self.progressSlider.maximumValue = CMTimeGetSeconds(self.player.currentItem.duration);
}
}
//
[self initTimer];
//5s dismiss bottomView
if (self.autoDismissTimer==nil) {
self.autoDismissTimer = [NSTimer timerWithTimeInterval:5.0 target:self selector:@selector(autoDismissBottomView:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.autoDismissTimer forMode:NSDefaultRunLoopMode];
}
if (self.delegate&&[self.delegate respondsToSelector:@selector(wmplayerReadyToPlay:WMPlayerStatus:)]) {
[self.delegate wmplayerReadyToPlay:self WMPlayerStatus:WMPlayerStatusReadyToPlay];
}
[self.loadingView stopAnimating];
// xx
if (self.seekTime) {
[self seekToTimeToPlay:self.seekTime];
}
}
break;
case AVPlayerStatusFailed:
{
self.state = WMPlayerStateFailed;
if (self.delegate&&[self.delegate respondsToSelector:@selector(wmplayerFailedPlay:WMPlayerStatus:)]) {
[self.delegate wmplayerFailedPlay:self WMPlayerStatus:WMPlayerStateFailed];
}
NSError *error = [self.player.currentItem error];
if (error) {
self.loadFailedLabel.hidden = NO;
[self bringSubviewToFront:self.loadFailedLabel];
[self.loadingView stopAnimating];
}
NSLog(@"===%@",error.description);
}
break;
}
}else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
//
NSTimeInterval timeInterval = [self availableDuration];
CMTime duration = self.currentItem.duration;
CGFloat totalDuration = CMTimeGetSeconds(duration);
//
self.loadingProgress.progressTintColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.7];
[self.loadingProgress setProgress:timeInterval / totalDuration animated:NO];
} else if ([keyPath isEqualToString:@"playbackBufferEmpty"]) {
[self.loadingView startAnimating];
//
if (self.currentItem.playbackBufferEmpty) {
self.state = WMPlayerStateBuffering;
[self loadedTimeRanges];
}
} else if ([keyPath isEqualToString:@"playbackLikelyToKeepUp"]) {
[self.loadingView stopAnimating];
//
if (self.currentItem.playbackLikelyToKeepUp && self.state == WMPlayerStateBuffering){
self.state = WMPlayerStatePlaying;
}
}
}
}
/**
*
*/
- (void)loadedTimeRanges
{
self.state = WMPlayerStateBuffering;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self play];
[self.loadingView stopAnimating];
});
}
#pragma mark
#pragma mark autoDismissBottomView
-(void)autoDismissBottomView:(NSTimer *)timer{
if (self.player.rate==.0f&&self.currentTime != self.duration) {//
}else if(self.player.rate==1.0f){
if (self.bottomView.alpha==1.0) {
[UIView animateWithDuration:0.5 animations:^{
self.bottomView.alpha = 0.0;
self.closeBtn.alpha = 0.0;
self.topView.alpha = 0.0;
} completion:^(BOOL finish){
}];
}
}
}
#pragma mark -
-(void)initTimer{
double interval = .1f;
CMTime playerDuration = [self playerItemDuration];
if (CMTIME_IS_INVALID(playerDuration))
{
return;
}
double duration = CMTimeGetSeconds(playerDuration);
if (isfinite(duration))
{
CGFloat width = CGRectGetWidth([self.progressSlider bounds]);
interval = 0.5f * duration / width;
}
__weak typeof(self) weakSelf = self;
self.playbackTimeObserver = [weakSelf.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(1.0, NSEC_PER_SEC) queue:dispatch_get_main_queue() /* If you pass NULL, the main queue is used. */
usingBlock:^(CMTime time){
[weakSelf syncScrubber];
}];
}
- (void)syncScrubber{
CMTime playerDuration = [self playerItemDuration];
if (CMTIME_IS_INVALID(playerDuration)){
self.progressSlider.minimumValue = 0.0;
return;
}
double duration = CMTimeGetSeconds(playerDuration);
if (isfinite(duration)){
float minValue = [self.progressSlider minimumValue];
float maxValue = [self.progressSlider maximumValue];
double nowTime = CMTimeGetSeconds([self.player currentTime]);
double remainTime = duration-nowTime;
self.leftTimeLabel.text = [self convertTime:nowTime];
self.rightTimeLabel.text = [self convertTime:remainTime];
if (self.isDragingSlider==YES) {//sliderslider
}else if(self.isDragingSlider==NO){
[self.progressSlider setValue:(maxValue - minValue) * nowTime / duration + minValue];
}
}
}
/**
* time
* @param seekTime
*/
- (void)seekToTimeToPlay:(double)time{
if (self.player&&self.player.currentItem.status == AVPlayerItemStatusReadyToPlay) {
if (time>[self duration]) {
time = [self duration];
}
if (time<=0) {
time=0.0;
}
// int32_t timeScale = self.player.currentItem.asset.duration.timescale;
//currentItem.asset.duration.timescale
/* A timescale of 1 means you can only specify whole seconds to seek to. The timescale is the number of parts per second. Use 600 for video, as Apple recommends, since it is a product of the common video frame rates like 50, 60, 25 and 24 frames per second*/
[self.player seekToTime:CMTimeMakeWithSeconds(time, _currentItem.currentTime.timescale) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:^(BOOL finished) {
}];
}
}
- (CMTime)playerItemDuration{
AVPlayerItem *playerItem = _currentItem;
if (playerItem.status == AVPlayerItemStatusReadyToPlay){
return([playerItem duration]);
}
return(kCMTimeInvalid);
}
- (NSString *)convertTime:(CGFloat)second{
NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
if (second/3600 >= 1) {
[[self dateFormatter] setDateFormat:@"HH:mm:ss"];
} else {
[[self dateFormatter] setDateFormat:@"mm:ss"];
}
NSString *newTime = [[self dateFormatter] stringFromDate:d];
return newTime;
}
/**
*
*
* @return
*/
- (NSTimeInterval)availableDuration {
NSArray *loadedTimeRanges = [_currentItem loadedTimeRanges];
CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];//
float startSeconds = CMTimeGetSeconds(timeRange.start);
float durationSeconds = CMTimeGetSeconds(timeRange.duration);
NSTimeInterval result = startSeconds + durationSeconds;//
return result;
}
- (NSDateFormatter *)dateFormatter {
if (!_dateFormatter) {
_dateFormatter = [[NSDateFormatter alloc] init];
}
return _dateFormatter;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
for(UITouch *touch in event.allTouches) {
self.firstPoint = [touch locationInView:self];
}
self.volumeSlider.value = systemSlider.value;
//,moved
self.originalPoint = self.firstPoint;
// UISlider *volumeSlider = (UISlider *)[self viewWithTag:1000];
// volumeSlider.value = systemSlider.value;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
for(UITouch *touch in event.allTouches) {
self.secondPoint = [touch locationInView:self];
}
//
CGFloat verValue =fabs(self.originalPoint.y - self.secondPoint.y);
CGFloat horValue = fabs(self.originalPoint.x - self.secondPoint.x);
//,
if (verValue > horValue) {//
//
if (self.isFullscreen) {//
//,
if (self.originalPoint.x <= kHalfHeight) {//:pointview()
/* ,y,0,600,N,
N/600,600,,1, */
systemSlider.value += (self.firstPoint.y - self.secondPoint.y)/600.0;
self.volumeSlider.value = systemSlider.value;
}else{//:pointview()
//
self.lightSlider.value += (self.firstPoint.y - self.secondPoint.y)/600.0;
[[UIScreen mainScreen] setBrightness:self.lightSlider.value];
}
}else{//
//,
if (self.originalPoint.x <= kHalfWidth) {//:pointview()
/* ,y,0,600,N,
N/600,600,,1, */
systemSlider.value += (self.firstPoint.y - self.secondPoint.y)/600.0;
self.volumeSlider.value = systemSlider.value;
}else{//:pointview()
//
self.lightSlider.value += (self.firstPoint.y - self.secondPoint.y)/600.0;
[[UIScreen mainScreen] setBrightness:self.lightSlider.value];
}
}
}else{//,
//600self.progressSlider,
//,progressSlider.value1,,progressSlider
self.progressSlider.value -= (self.firstPoint.x - self.secondPoint.x);
[self.player seekToTime:CMTimeMakeWithSeconds(self.progressSlider.value, self.currentItem.currentTime.timescale)];
//,
if (self.player.rate != 1.f) {
if ([self currentTime] == [self duration])
[self setCurrentTime:0.f];
self.playOrPauseBtn.selected = NO;
[self.player play];
}
}
self.firstPoint = self.secondPoint;
// systemSlider.value += (self.firstPoint.y - self.secondPoint.y)/500.0;
// UISlider *volumeSlider = (UISlider *)[self viewWithTag:1000];
// volumeSlider.value = systemSlider.value;
// self.firstPoint = self.secondPoint;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
self.firstPoint = self.secondPoint = CGPointZero;
}
//
-(void )resetWMPlayer{
self.currentItem = nil;
self.seekTime = 0;
//
[[NSNotificationCenter defaultCenter] removeObserver:self];
//
[self.autoDismissTimer invalidate];
self.autoDismissTimer = nil;
//
[self.player pause];
// layer
[self.playerLayer removeFromSuperlayer];
// PlayerItemnil
[self.player replaceCurrentItemWithPlayerItem:nil];
// playernil
self.player = nil;
}
-(void)dealloc{
NSLog(@"WMPlayer dealloc");
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self.player.currentItem cancelPendingSeeks];
[self.player.currentItem.asset cancelLoading];
[self.player pause];
[self.player removeTimeObserver:self.playbackTimeObserver];
//
[_currentItem removeObserver:self forKeyPath:@"status"];
[_currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
[_currentItem removeObserver:self forKeyPath:@"playbackBufferEmpty"];
[_currentItem removeObserver:self forKeyPath:@"playbackLikelyToKeepUp"];
[self.playerLayer removeFromSuperlayer];
[self.player replaceCurrentItemWithPlayerItem:nil];
self.player = nil;
self.currentItem = nil;
self.playOrPauseBtn = nil;
self.playerLayer = nil;
self.autoDismissTimer = nil;
}
- (NSString *)version{
return @"2.0.0";
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/WMPlayer/WMPlayer.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 8,208
|
```objective-c
//
// YYDiskCache.h
// YYKit <path_to_url
//
// Created by ibireme on 15/2/11.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
YYDiskCache is a thread-safe cache that stores key-value pairs backed by SQLite
and file system (similar to NSURLCache's disk cache).
YYDiskCache has these features:
* It use LRU (least-recently-used) to remove objects.
* It can be controlled by cost, count, and age.
* It can be configured to automatically evict objects when there's no free disk space.
* It can automatically decide the storage type (sqlite/file) for each object to get
better performance.
You may compile the latest version of sqlite and ignore the libsqlite3.dylib in
iOS system to get 2x~4x speed up.
*/
@interface YYDiskCache : NSObject
#pragma mark - Attribute
///=============================================================================
/// @name Attribute
///=============================================================================
/** The name of the cache. Default is nil. */
@property (nullable, copy) NSString *name;
/** The path of the cache (read-only). */
@property (readonly) NSString *path;
/**
If the object's data size (in bytes) is larger than this value, then object will
be stored as a file, otherwise the object will be stored in sqlite.
0 means all objects will be stored as separated files, NSUIntegerMax means all
objects will be stored in sqlite.
The default value is 20480 (20KB).
*/
@property (readonly) NSUInteger inlineThreshold;
/**
If this block is not nil, then the block will be used to archive object instead
of NSKeyedArchiver. You can use this block to support the objects which do not
conform to the `NSCoding` protocol.
The default value is nil.
*/
@property (nullable, copy) NSData *(^customArchiveBlock)(id object);
/**
If this block is not nil, then the block will be used to unarchive object instead
of NSKeyedUnarchiver. You can use this block to support the objects which do not
conform to the `NSCoding` protocol.
The default value is nil.
*/
@property (nullable, copy) id (^customUnarchiveBlock)(NSData *data);
/**
When an object needs to be saved as a file, this block will be invoked to generate
a file name for a specified key. If the block is nil, the cache use md5(key) as
default file name.
The default value is nil.
*/
@property (nullable, copy) NSString *(^customFileNameBlock)(NSString *key);
#pragma mark - Limit
///=============================================================================
/// @name Limit
///=============================================================================
/**
The maximum number of objects the cache should hold.
@discussion The default value is NSUIntegerMax, which means no limit.
This is not a strict limit if the cache goes over the limit, some objects in the
cache could be evicted later in background queue.
*/
@property NSUInteger countLimit;
/**
The maximum total cost that the cache can hold before it starts evicting objects.
@discussion The default value is NSUIntegerMax, which means no limit.
This is not a strict limit if the cache goes over the limit, some objects in the
cache could be evicted later in background queue.
*/
@property NSUInteger costLimit;
/**
The maximum expiry time of objects in cache.
@discussion The default value is DBL_MAX, which means no limit.
This is not a strict limit if an object goes over the limit, the objects could
be evicted later in background queue.
*/
@property NSTimeInterval ageLimit;
/**
The minimum free disk space (in bytes) which the cache should kept.
@discussion The default value is 0, which means no limit.
If the free disk space is lower than this value, the cache will remove objects
to free some disk space. This is not a strict limitif the free disk space goes
over the limit, the objects could be evicted later in background queue.
*/
@property NSUInteger freeDiskSpaceLimit;
/**
The auto trim check time interval in seconds. Default is 60 (1 minute).
@discussion The cache holds an internal timer to check whether the cache reaches
its limits, and if the limit is reached, it begins to evict objects.
*/
@property NSTimeInterval autoTrimInterval;
/**
Set `YES` to enable error logs for debug.
*/
@property BOOL errorLogsEnabled;
#pragma mark - Initializer
///=============================================================================
/// @name Initializer
///=============================================================================
- (instancetype)init UNAVAILABLE_ATTRIBUTE;
+ (instancetype)new UNAVAILABLE_ATTRIBUTE;
/**
Create a new cache based on the specified path.
@param path Full path of a directory in which the cache will write data.
Once initialized you should not read and write to this directory.
@return A new cache object, or nil if an error occurs.
@warning If the cache instance for the specified path already exists in memory,
this method will return it directly, instead of creating a new instance.
*/
- (nullable instancetype)initWithPath:(NSString *)path;
/**
The designated initializer.
@param path Full path of a directory in which the cache will write data.
Once initialized you should not read and write to this directory.
@param threshold The data store inline threshold in bytes. If the object's data
size (in bytes) is larger than this value, then object will be stored as a
file, otherwise the object will be stored in sqlite. 0 means all objects will
be stored as separated files, NSUIntegerMax means all objects will be stored
in sqlite. If you don't know your object's size, 20480 is a good choice.
After first initialized you should not change this value of the specified path.
@return A new cache object, or nil if an error occurs.
@warning If the cache instance for the specified path already exists in memory,
this method will return it directly, instead of creating a new instance.
*/
- (nullable instancetype)initWithPath:(NSString *)path
inlineThreshold:(NSUInteger)threshold NS_DESIGNATED_INITIALIZER;
#pragma mark - Access Methods
///=============================================================================
/// @name Access Methods
///=============================================================================
/**
Returns a boolean value that indicates whether a given key is in cache.
This method may blocks the calling thread until file read finished.
@param key A string identifying the value. If nil, just return NO.
@return Whether the key is in cache.
*/
- (BOOL)containsObjectForKey:(NSString *)key;
/**
Returns a boolean value with the block that indicates whether a given key is in cache.
This method returns immediately and invoke the passed block in background queue
when the operation finished.
@param key A string identifying the value. If nil, just return NO.
@param block A block which will be invoked in background queue when finished.
*/
- (void)containsObjectForKey:(NSString *)key withBlock:(void(^)(NSString *key, BOOL contains))block;
/**
Returns the value associated with a given key.
This method may blocks the calling thread until file read finished.
@param key A string identifying the value. If nil, just return nil.
@return The value associated with key, or nil if no value is associated with key.
*/
- (nullable id<NSCoding>)objectForKey:(NSString *)key;
/**
Returns the value associated with a given key.
This method returns immediately and invoke the passed block in background queue
when the operation finished.
@param key A string identifying the value. If nil, just return nil.
@param block A block which will be invoked in background queue when finished.
*/
- (void)objectForKey:(NSString *)key withBlock:(void(^)(NSString *key, id<NSCoding> _Nullable object))block;
/**
Sets the value of the specified key in the cache.
This method may blocks the calling thread until file write finished.
@param object The object to be stored in the cache. If nil, it calls `removeObjectForKey:`.
@param key The key with which to associate the value. If nil, this method has no effect.
*/
- (void)setObject:(nullable id<NSCoding>)object forKey:(NSString *)key;
/**
Sets the value of the specified key in the cache.
This method returns immediately and invoke the passed block in background queue
when the operation finished.
@param object The object to be stored in the cache. If nil, it calls `removeObjectForKey:`.
@param block A block which will be invoked in background queue when finished.
*/
- (void)setObject:(nullable id<NSCoding>)object forKey:(NSString *)key withBlock:(void(^)(void))block;
/**
Removes the value of the specified key in the cache.
This method may blocks the calling thread until file delete finished.
@param key The key identifying the value to be removed. If nil, this method has no effect.
*/
- (void)removeObjectForKey:(NSString *)key;
/**
Removes the value of the specified key in the cache.
This method returns immediately and invoke the passed block in background queue
when the operation finished.
@param key The key identifying the value to be removed. If nil, this method has no effect.
@param block A block which will be invoked in background queue when finished.
*/
- (void)removeObjectForKey:(NSString *)key withBlock:(void(^)(NSString *key))block;
/**
Empties the cache.
This method may blocks the calling thread until file delete finished.
*/
- (void)removeAllObjects;
/**
Empties the cache.
This method returns immediately and invoke the passed block in background queue
when the operation finished.
@param block A block which will be invoked in background queue when finished.
*/
- (void)removeAllObjectsWithBlock:(void(^)(void))block;
/**
Empties the cache with block.
This method returns immediately and executes the clear operation with block in background.
@warning You should not send message to this instance in these blocks.
@param progress This block will be invoked during removing, pass nil to ignore.
@param end This block will be invoked at the end, pass nil to ignore.
*/
- (void)removeAllObjectsWithProgressBlock:(nullable void(^)(int removedCount, int totalCount))progress
endBlock:(nullable void(^)(BOOL error))end;
/**
Returns the number of objects in this cache.
This method may blocks the calling thread until file read finished.
@return The total objects count.
*/
- (NSInteger)totalCount;
/**
Get the number of objects in this cache.
This method returns immediately and invoke the passed block in background queue
when the operation finished.
@param block A block which will be invoked in background queue when finished.
*/
- (void)totalCountWithBlock:(void(^)(NSInteger totalCount))block;
/**
Returns the total cost (in bytes) of objects in this cache.
This method may blocks the calling thread until file read finished.
@return The total objects cost in bytes.
*/
- (NSInteger)totalCost;
/**
Get the total cost (in bytes) of objects in this cache.
This method returns immediately and invoke the passed block in background queue
when the operation finished.
@param block A block which will be invoked in background queue when finished.
*/
- (void)totalCostWithBlock:(void(^)(NSInteger totalCost))block;
#pragma mark - Trim
///=============================================================================
/// @name Trim
///=============================================================================
/**
Removes objects from the cache use LRU, until the `totalCount` is below the specified value.
This method may blocks the calling thread until operation finished.
@param count The total count allowed to remain after the cache has been trimmed.
*/
- (void)trimToCount:(NSUInteger)count;
/**
Removes objects from the cache use LRU, until the `totalCount` is below the specified value.
This method returns immediately and invoke the passed block in background queue
when the operation finished.
@param count The total count allowed to remain after the cache has been trimmed.
@param block A block which will be invoked in background queue when finished.
*/
- (void)trimToCount:(NSUInteger)count withBlock:(void(^)(void))block;
/**
Removes objects from the cache use LRU, until the `totalCost` is below the specified value.
This method may blocks the calling thread until operation finished.
@param cost The total cost allowed to remain after the cache has been trimmed.
*/
- (void)trimToCost:(NSUInteger)cost;
/**
Removes objects from the cache use LRU, until the `totalCost` is below the specified value.
This method returns immediately and invoke the passed block in background queue
when the operation finished.
@param cost The total cost allowed to remain after the cache has been trimmed.
@param block A block which will be invoked in background queue when finished.
*/
- (void)trimToCost:(NSUInteger)cost withBlock:(void(^)(void))block;
/**
Removes objects from the cache use LRU, until all expiry objects removed by the specified value.
This method may blocks the calling thread until operation finished.
@param age The maximum age of the object.
*/
- (void)trimToAge:(NSTimeInterval)age;
/**
Removes objects from the cache use LRU, until all expiry objects removed by the specified value.
This method returns immediately and invoke the passed block in background queue
when the operation finished.
@param age The maximum age of the object.
@param block A block which will be invoked in background queue when finished.
*/
- (void)trimToAge:(NSTimeInterval)age withBlock:(void(^)(void))block;
#pragma mark - Extended Data
///=============================================================================
/// @name Extended Data
///=============================================================================
/**
Get extended data from an object.
@discussion See 'setExtendedData:toObject:' for more information.
@param object An object.
@return The extended data.
*/
+ (nullable NSData *)getExtendedDataFromObject:(id)object;
/**
Set extended data to an object.
@discussion You can set any extended data to an object before you save the object
to disk cache. The extended data will also be saved with this object. You can get
the extended data later with "getExtendedDataFromObject:".
@param extendedData The extended data (pass nil to remove).
@param object The object.
*/
+ (void)setExtendedData:(nullable NSData *)extendedData toObject:(id)object;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Cache/YYDiskCache.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 3,052
|
```objective-c
//
// YYMemoryCache.m
// YYKit <path_to_url
//
// Created by ibireme on 15/2/7.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "YYMemoryCache.h"
#import <UIKit/UIKit.h>
#import <CoreFoundation/CoreFoundation.h>
#import <QuartzCore/QuartzCore.h>
#import <pthread.h>
#if __has_include("YYDispatchQueuePool.h")
#import "YYDispatchQueuePool.h"
#endif
#ifdef YYDispatchQueuePool_h
static inline dispatch_queue_t YYMemoryCacheGetReleaseQueue() {
return YYDispatchQueueGetForQOS(NSQualityOfServiceUtility);
}
#else
static inline dispatch_queue_t YYMemoryCacheGetReleaseQueue() {
return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
}
#endif
/**
A node in linked map.
Typically, you should not use this class directly.
*/
@interface _YYLinkedMapNode : NSObject {
@package
__unsafe_unretained _YYLinkedMapNode *_prev; // retained by dic
__unsafe_unretained _YYLinkedMapNode *_next; // retained by dic
id _key;
id _value;
NSUInteger _cost;
NSTimeInterval _time;
}
@end
@implementation _YYLinkedMapNode
@end
/**
A linked map used by YYMemoryCache.
It's not thread-safe and does not validate the parameters.
Typically, you should not use this class directly.
*/
@interface _YYLinkedMap : NSObject {
@package
CFMutableDictionaryRef _dic; // do not set object directly
NSUInteger _totalCost;
NSUInteger _totalCount;
_YYLinkedMapNode *_head; // MRU, do not change it directly
_YYLinkedMapNode *_tail; // LRU, do not change it directly
BOOL _releaseOnMainThread;
BOOL _releaseAsynchronously;
}
/// Insert a node at head and update the total cost.
/// Node and node.key should not be nil.
- (void)insertNodeAtHead:(_YYLinkedMapNode *)node;
/// Bring a inner node to header.
/// Node should already inside the dic.
- (void)bringNodeToHead:(_YYLinkedMapNode *)node;
/// Remove a inner node and update the total cost.
/// Node should already inside the dic.
- (void)removeNode:(_YYLinkedMapNode *)node;
/// Remove tail node if exist.
- (_YYLinkedMapNode *)removeTailNode;
/// Remove all node in background queue.
- (void)removeAll;
@end
@implementation _YYLinkedMap
- (instancetype)init {
self = [super init];
_dic = CFDictionaryCreateMutable(CFAllocatorGetDefault(), 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
_releaseOnMainThread = NO;
_releaseAsynchronously = YES;
return self;
}
- (void)dealloc {
CFRelease(_dic);
}
- (void)insertNodeAtHead:(_YYLinkedMapNode *)node {
CFDictionarySetValue(_dic, (__bridge const void *)(node->_key), (__bridge const void *)(node));
_totalCost += node->_cost;
_totalCount++;
if (_head) {
node->_next = _head;
_head->_prev = node;
_head = node;
} else {
_head = _tail = node;
}
}
- (void)bringNodeToHead:(_YYLinkedMapNode *)node {
if (_head == node) return;
if (_tail == node) {
_tail = node->_prev;
_tail->_next = nil;
} else {
node->_next->_prev = node->_prev;
node->_prev->_next = node->_next;
}
node->_next = _head;
node->_prev = nil;
_head->_prev = node;
_head = node;
}
- (void)removeNode:(_YYLinkedMapNode *)node {
CFDictionaryRemoveValue(_dic, (__bridge const void *)(node->_key));
_totalCost -= node->_cost;
_totalCount--;
if (node->_next) node->_next->_prev = node->_prev;
if (node->_prev) node->_prev->_next = node->_next;
if (_head == node) _head = node->_next;
if (_tail == node) _tail = node->_prev;
}
- (_YYLinkedMapNode *)removeTailNode {
if (!_tail) return nil;
_YYLinkedMapNode *tail = _tail;
CFDictionaryRemoveValue(_dic, (__bridge const void *)(_tail->_key));
_totalCost -= _tail->_cost;
_totalCount--;
if (_head == _tail) {
_head = _tail = nil;
} else {
_tail = _tail->_prev;
_tail->_next = nil;
}
return tail;
}
- (void)removeAll {
_totalCost = 0;
_totalCount = 0;
_head = nil;
_tail = nil;
if (CFDictionaryGetCount(_dic) > 0) {
CFMutableDictionaryRef holder = _dic;
_dic = CFDictionaryCreateMutable(CFAllocatorGetDefault(), 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
if (_releaseAsynchronously) {
dispatch_queue_t queue = _releaseOnMainThread ? dispatch_get_main_queue() : YYMemoryCacheGetReleaseQueue();
dispatch_async(queue, ^{
CFRelease(holder); // hold and release in specified queue
});
} else if (_releaseOnMainThread && !pthread_main_np()) {
dispatch_async(dispatch_get_main_queue(), ^{
CFRelease(holder); // hold and release in specified queue
});
} else {
CFRelease(holder);
}
}
}
@end
@implementation YYMemoryCache {
pthread_mutex_t _lock;
_YYLinkedMap *_lru;
dispatch_queue_t _queue;
}
- (void)_trimRecursively {
__weak typeof(self) _self = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_autoTrimInterval * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
__strong typeof(_self) self = _self;
if (!self) return;
[self _trimInBackground];
[self _trimRecursively];
});
}
- (void)_trimInBackground {
dispatch_async(_queue, ^{
[self _trimToCost:self->_costLimit];
[self _trimToCount:self->_countLimit];
[self _trimToAge:self->_ageLimit];
});
}
- (void)_trimToCost:(NSUInteger)costLimit {
BOOL finish = NO;
pthread_mutex_lock(&_lock);
if (costLimit == 0) {
[_lru removeAll];
finish = YES;
} else if (_lru->_totalCost <= costLimit) {
finish = YES;
}
pthread_mutex_unlock(&_lock);
if (finish) return;
NSMutableArray *holder = [NSMutableArray new];
while (!finish) {
if (pthread_mutex_trylock(&_lock) == 0) {
if (_lru->_totalCost > costLimit) {
_YYLinkedMapNode *node = [_lru removeTailNode];
if (node) [holder addObject:node];
} else {
finish = YES;
}
pthread_mutex_unlock(&_lock);
} else {
usleep(10 * 1000); //10 ms
}
}
if (holder.count) {
dispatch_queue_t queue = _lru->_releaseOnMainThread ? dispatch_get_main_queue() : YYMemoryCacheGetReleaseQueue();
dispatch_async(queue, ^{
[holder count]; // release in queue
});
}
}
- (void)_trimToCount:(NSUInteger)countLimit {
BOOL finish = NO;
pthread_mutex_lock(&_lock);
if (countLimit == 0) {
[_lru removeAll];
finish = YES;
} else if (_lru->_totalCount <= countLimit) {
finish = YES;
}
pthread_mutex_unlock(&_lock);
if (finish) return;
NSMutableArray *holder = [NSMutableArray new];
while (!finish) {
if (pthread_mutex_trylock(&_lock) == 0) {
if (_lru->_totalCount > countLimit) {
_YYLinkedMapNode *node = [_lru removeTailNode];
if (node) [holder addObject:node];
} else {
finish = YES;
}
pthread_mutex_unlock(&_lock);
} else {
usleep(10 * 1000); //10 ms
}
}
if (holder.count) {
dispatch_queue_t queue = _lru->_releaseOnMainThread ? dispatch_get_main_queue() : YYMemoryCacheGetReleaseQueue();
dispatch_async(queue, ^{
[holder count]; // release in queue
});
}
}
- (void)_trimToAge:(NSTimeInterval)ageLimit {
BOOL finish = NO;
NSTimeInterval now = CACurrentMediaTime();
pthread_mutex_lock(&_lock);
if (ageLimit <= 0) {
[_lru removeAll];
finish = YES;
} else if (!_lru->_tail || (now - _lru->_tail->_time) <= ageLimit) {
finish = YES;
}
pthread_mutex_unlock(&_lock);
if (finish) return;
NSMutableArray *holder = [NSMutableArray new];
while (!finish) {
if (pthread_mutex_trylock(&_lock) == 0) {
if (_lru->_tail && (now - _lru->_tail->_time) > ageLimit) {
_YYLinkedMapNode *node = [_lru removeTailNode];
if (node) [holder addObject:node];
} else {
finish = YES;
}
pthread_mutex_unlock(&_lock);
} else {
usleep(10 * 1000); //10 ms
}
}
if (holder.count) {
dispatch_queue_t queue = _lru->_releaseOnMainThread ? dispatch_get_main_queue() : YYMemoryCacheGetReleaseQueue();
dispatch_async(queue, ^{
[holder count]; // release in queue
});
}
}
- (void)_appDidReceiveMemoryWarningNotification {
if (self.didReceiveMemoryWarningBlock) {
self.didReceiveMemoryWarningBlock(self);
}
if (self.shouldRemoveAllObjectsOnMemoryWarning) {
[self removeAllObjects];
}
}
- (void)_appDidEnterBackgroundNotification {
if (self.didEnterBackgroundBlock) {
self.didEnterBackgroundBlock(self);
}
if (self.shouldRemoveAllObjectsWhenEnteringBackground) {
[self removeAllObjects];
}
}
#pragma mark - public
- (instancetype)init {
self = super.init;
pthread_mutex_init(&_lock, NULL);
_lru = [_YYLinkedMap new];
_queue = dispatch_queue_create("com.ibireme.cache.memory", DISPATCH_QUEUE_SERIAL);
_countLimit = NSUIntegerMax;
_costLimit = NSUIntegerMax;
_ageLimit = DBL_MAX;
_autoTrimInterval = 5.0;
_shouldRemoveAllObjectsOnMemoryWarning = YES;
_shouldRemoveAllObjectsWhenEnteringBackground = YES;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_appDidReceiveMemoryWarningNotification) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_appDidEnterBackgroundNotification) name:UIApplicationDidEnterBackgroundNotification object:nil];
[self _trimRecursively];
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
[_lru removeAll];
pthread_mutex_destroy(&_lock);
}
- (NSUInteger)totalCount {
pthread_mutex_lock(&_lock);
NSUInteger count = _lru->_totalCount;
pthread_mutex_unlock(&_lock);
return count;
}
- (NSUInteger)totalCost {
pthread_mutex_lock(&_lock);
NSUInteger totalCost = _lru->_totalCost;
pthread_mutex_unlock(&_lock);
return totalCost;
}
- (BOOL)releaseOnMainThread {
pthread_mutex_lock(&_lock);
BOOL releaseOnMainThread = _lru->_releaseOnMainThread;
pthread_mutex_unlock(&_lock);
return releaseOnMainThread;
}
- (void)setReleaseOnMainThread:(BOOL)releaseOnMainThread {
pthread_mutex_lock(&_lock);
_lru->_releaseOnMainThread = releaseOnMainThread;
pthread_mutex_unlock(&_lock);
}
- (BOOL)releaseAsynchronously {
pthread_mutex_lock(&_lock);
BOOL releaseAsynchronously = _lru->_releaseAsynchronously;
pthread_mutex_unlock(&_lock);
return releaseAsynchronously;
}
- (void)setReleaseAsynchronously:(BOOL)releaseAsynchronously {
pthread_mutex_lock(&_lock);
_lru->_releaseAsynchronously = releaseAsynchronously;
pthread_mutex_unlock(&_lock);
}
- (BOOL)containsObjectForKey:(id)key {
if (!key) return NO;
pthread_mutex_lock(&_lock);
BOOL contains = CFDictionaryContainsKey(_lru->_dic, (__bridge const void *)(key));
pthread_mutex_unlock(&_lock);
return contains;
}
- (id)objectForKey:(id)key {
if (!key) return nil;
pthread_mutex_lock(&_lock);
_YYLinkedMapNode *node = CFDictionaryGetValue(_lru->_dic, (__bridge const void *)(key));
if (node) {
node->_time = CACurrentMediaTime();
[_lru bringNodeToHead:node];
}
pthread_mutex_unlock(&_lock);
return node ? node->_value : nil;
}
- (void)setObject:(id)object forKey:(id)key {
[self setObject:object forKey:key withCost:0];
}
- (void)setObject:(id)object forKey:(id)key withCost:(NSUInteger)cost {
if (!key) return;
if (!object) {
[self removeObjectForKey:key];
return;
}
pthread_mutex_lock(&_lock);
_YYLinkedMapNode *node = CFDictionaryGetValue(_lru->_dic, (__bridge const void *)(key));
NSTimeInterval now = CACurrentMediaTime();
if (node) {
_lru->_totalCost -= node->_cost;
_lru->_totalCost += cost;
node->_cost = cost;
node->_time = now;
node->_value = object;
[_lru bringNodeToHead:node];
} else {
node = [_YYLinkedMapNode new];
node->_cost = cost;
node->_time = now;
node->_key = key;
node->_value = object;
[_lru insertNodeAtHead:node];
}
if (_lru->_totalCost > _costLimit) {
dispatch_async(_queue, ^{
[self trimToCost:_costLimit];
});
}
if (_lru->_totalCount > _countLimit) {
_YYLinkedMapNode *node = [_lru removeTailNode];
if (_lru->_releaseAsynchronously) {
dispatch_queue_t queue = _lru->_releaseOnMainThread ? dispatch_get_main_queue() : YYMemoryCacheGetReleaseQueue();
dispatch_async(queue, ^{
[node class]; //hold and release in queue
});
} else if (_lru->_releaseOnMainThread && !pthread_main_np()) {
dispatch_async(dispatch_get_main_queue(), ^{
[node class]; //hold and release in queue
});
}
}
pthread_mutex_unlock(&_lock);
}
- (void)removeObjectForKey:(id)key {
if (!key) return;
pthread_mutex_lock(&_lock);
_YYLinkedMapNode *node = CFDictionaryGetValue(_lru->_dic, (__bridge const void *)(key));
if (node) {
[_lru removeNode:node];
if (_lru->_releaseAsynchronously) {
dispatch_queue_t queue = _lru->_releaseOnMainThread ? dispatch_get_main_queue() : YYMemoryCacheGetReleaseQueue();
dispatch_async(queue, ^{
[node class]; //hold and release in queue
});
} else if (_lru->_releaseOnMainThread && !pthread_main_np()) {
dispatch_async(dispatch_get_main_queue(), ^{
[node class]; //hold and release in queue
});
}
}
pthread_mutex_unlock(&_lock);
}
- (void)removeAllObjects {
pthread_mutex_lock(&_lock);
[_lru removeAll];
pthread_mutex_unlock(&_lock);
}
- (void)trimToCount:(NSUInteger)count {
if (count == 0) {
[self removeAllObjects];
return;
}
[self _trimToCount:count];
}
- (void)trimToCost:(NSUInteger)cost {
[self _trimToCost:cost];
}
- (void)trimToAge:(NSTimeInterval)age {
[self _trimToAge:age];
}
- (NSString *)description {
if (_name) return [NSString stringWithFormat:@"<%@: %p> (%@)", self.class, self, _name];
else return [NSString stringWithFormat:@"<%@: %p>", self.class, self];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Cache/YYMemoryCache.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 3,712
|
```objective-c
//
// YYCache.m
// YYKit <path_to_url
//
// Created by ibireme on 15/2/13.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "YYCache.h"
#import "YYMemoryCache.h"
#import "YYDiskCache.h"
@implementation YYCache
- (instancetype) init {
NSLog(@"Use \"initWithName\" or \"initWithPath\" to create YYCache instance.");
return [self initWithPath:@""];
}
- (instancetype)initWithName:(NSString *)name {
if (name.length == 0) return nil;
NSString *cacheFolder = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
NSString *path = [cacheFolder stringByAppendingPathComponent:name];
return [self initWithPath:path];
}
- (instancetype)initWithPath:(NSString *)path {
if (path.length == 0) return nil;
YYDiskCache *diskCache = [[YYDiskCache alloc] initWithPath:path];
if (!diskCache) return nil;
NSString *name = [path lastPathComponent];
YYMemoryCache *memoryCache = [YYMemoryCache new];
memoryCache.name = name;
self = [super init];
_name = name;
_diskCache = diskCache;
_memoryCache = memoryCache;
return self;
}
+ (instancetype)cacheWithName:(NSString *)name {
return [[self alloc] initWithName:name];
}
+ (instancetype)cacheWithPath:(NSString *)path {
return [[self alloc] initWithPath:path];
}
- (BOOL)containsObjectForKey:(NSString *)key {
return [_memoryCache containsObjectForKey:key] || [_diskCache containsObjectForKey:key];
}
- (void)containsObjectForKey:(NSString *)key withBlock:(void (^)(NSString *key, BOOL contains))block {
if (!block) return;
if ([_memoryCache containsObjectForKey:key]) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
block(key, YES);
});
} else {
[_diskCache containsObjectForKey:key withBlock:block];
}
}
- (id<NSCoding>)objectForKey:(NSString *)key {
id<NSCoding> object = [_memoryCache objectForKey:key];
if (!object) {
object = [_diskCache objectForKey:key];
if (object) {
[_memoryCache setObject:object forKey:key];
}
}
return object;
}
- (void)objectForKey:(NSString *)key withBlock:(void (^)(NSString *key, id<NSCoding> object))block {
if (!block) return;
id<NSCoding> object = [_memoryCache objectForKey:key];
if (object) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
block(key, object);
});
} else {
[_diskCache objectForKey:key withBlock:^(NSString *key, id<NSCoding> object) {
if (object && ![_memoryCache objectForKey:key]) {
[_memoryCache setObject:object forKey:key];
}
block(key, object);
}];
}
}
- (void)setObject:(id<NSCoding>)object forKey:(NSString *)key {
[_memoryCache setObject:object forKey:key];
[_diskCache setObject:object forKey:key];
}
- (void)setObject:(id<NSCoding>)object forKey:(NSString *)key withBlock:(void (^)(void))block {
[_memoryCache setObject:object forKey:key];
[_diskCache setObject:object forKey:key withBlock:block];
}
- (void)removeObjectForKey:(NSString *)key {
[_memoryCache removeObjectForKey:key];
[_diskCache removeObjectForKey:key];
}
- (void)removeObjectForKey:(NSString *)key withBlock:(void (^)(NSString *key))block {
[_memoryCache removeObjectForKey:key];
[_diskCache removeObjectForKey:key withBlock:block];
}
- (void)removeAllObjects {
[_memoryCache removeAllObjects];
[_diskCache removeAllObjects];
}
- (void)removeAllObjectsWithBlock:(void(^)(void))block {
[_memoryCache removeAllObjects];
[_diskCache removeAllObjectsWithBlock:block];
}
- (void)removeAllObjectsWithProgressBlock:(void(^)(int removedCount, int totalCount))progress
endBlock:(void(^)(BOOL error))end {
[_memoryCache removeAllObjects];
[_diskCache removeAllObjectsWithProgressBlock:progress endBlock:end];
}
- (NSString *)description {
if (_name) return [NSString stringWithFormat:@"<%@: %p> (%@)", self.class, self, _name];
else return [NSString stringWithFormat:@"<%@: %p>", self.class, self];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Cache/YYCache.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,010
|
```objective-c
//
// YYKVStorage.h
// YYKit <path_to_url
//
// Created by ibireme on 15/4/22.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
YYKVStorageItem is used by `YYKVStorage` to store key-value pair and meta data.
Typically, you should not use this class directly.
*/
@interface YYKVStorageItem : NSObject
@property (nonatomic, strong) NSString *key; ///< key
@property (nonatomic, strong) NSData *value; ///< value
@property (nullable, nonatomic, strong) NSString *filename; ///< filename (nil if inline)
@property (nonatomic) int size; ///< value's size in bytes
@property (nonatomic) int modTime; ///< modification unix timestamp
@property (nonatomic) int accessTime; ///< last access unix timestamp
@property (nullable, nonatomic, strong) NSData *extendedData; ///< extended data (nil if no extended data)
@end
/**
Storage type, indicated where the `YYKVStorageItem.value` stored.
@discussion Typically, write data to sqlite is faster than extern file, but
reading performance is dependent on data size. In my test (on iPhone 6 64G),
read data from extern file is faster than from sqlite when the data is larger
than 20KB.
* If you want to store large number of small datas (such as contacts cache),
use YYKVStorageTypeSQLite to get better performance.
* If you want to store large files (such as image cache),
use YYKVStorageTypeFile to get better performance.
* You can use YYKVStorageTypeMixed and choice your storage type for each item.
See <path_to_url for more information.
*/
typedef NS_ENUM(NSUInteger, YYKVStorageType) {
/// The `value` is stored as a file in file system.
YYKVStorageTypeFile = 0,
/// The `value` is stored in sqlite with blob type.
YYKVStorageTypeSQLite = 1,
/// The `value` is stored in file system or sqlite based on your choice.
YYKVStorageTypeMixed = 2,
};
/**
YYKVStorage is a key-value storage based on sqlite and file system.
Typically, you should not use this class directly.
@discussion The designated initializer for YYKVStorage is `initWithPath:type:`.
After initialized, a directory is created based on the `path` to hold key-value data.
Once initialized you should not read or write this directory without the instance.
You may compile the latest version of sqlite and ignore the libsqlite3.dylib in
iOS system to get 2x~4x speed up.
@warning The instance of this class is *NOT* thread safe, you need to make sure
that there's only one thread to access the instance at the same time. If you really
need to process large amounts of data in multi-thread, you should split the data
to multiple KVStorage instance (sharding).
*/
@interface YYKVStorage : NSObject
#pragma mark - Attribute
///=============================================================================
/// @name Attribute
///=============================================================================
@property (nonatomic, readonly) NSString *path; ///< The path of this storage.
@property (nonatomic, readonly) YYKVStorageType type; ///< The type of this storage.
@property (nonatomic) BOOL errorLogsEnabled; ///< Set `YES` to enable error logs for debug.
#pragma mark - Initializer
///=============================================================================
/// @name Initializer
///=============================================================================
- (instancetype)init UNAVAILABLE_ATTRIBUTE;
+ (instancetype)new UNAVAILABLE_ATTRIBUTE;
/**
The designated initializer.
@param path Full path of a directory in which the storage will write data. If
the directory is not exists, it will try to create one, otherwise it will
read the data in this directory.
@param type The storage type. After first initialized you should not change the
type of the specified path.
@return A new storage object, or nil if an error occurs.
@warning Multiple instances with the same path will make the storage unstable.
*/
- (nullable instancetype)initWithPath:(NSString *)path type:(YYKVStorageType)type NS_DESIGNATED_INITIALIZER;
#pragma mark - Save Items
///=============================================================================
/// @name Save Items
///=============================================================================
/**
Save an item or update the item with 'key' if it already exists.
@discussion This method will save the item.key, item.value, item.filename and
item.extendedData to disk or sqlite, other properties will be ignored. item.key
and item.value should not be empty (nil or zero length).
If the `type` is YYKVStorageTypeFile, then the item.filename should not be empty.
If the `type` is YYKVStorageTypeSQLite, then the item.filename will be ignored.
It the `type` is YYKVStorageTypeMixed, then the item.value will be saved to file
system if the item.filename is not empty, otherwise it will be saved to sqlite.
@param item An item.
@return Whether succeed.
*/
- (BOOL)saveItem:(YYKVStorageItem *)item;
/**
Save an item or update the item with 'key' if it already exists.
@discussion This method will save the key-value pair to sqlite. If the `type` is
YYKVStorageTypeFile, then this method will failed.
@param key The key, should not be empty (nil or zero length).
@param value The key, should not be empty (nil or zero length).
@return Whether succeed.
*/
- (BOOL)saveItemWithKey:(NSString *)key value:(NSData *)value;
/**
Save an item or update the item with 'key' if it already exists.
@discussion
If the `type` is YYKVStorageTypeFile, then the `filename` should not be empty.
If the `type` is YYKVStorageTypeSQLite, then the `filename` will be ignored.
It the `type` is YYKVStorageTypeMixed, then the `value` will be saved to file
system if the `filename` is not empty, otherwise it will be saved to sqlite.
@param key The key, should not be empty (nil or zero length).
@param value The key, should not be empty (nil or zero length).
@param filename The filename.
@param extendedData The extended data for this item (pass nil to ignore it).
@return Whether succeed.
*/
- (BOOL)saveItemWithKey:(NSString *)key
value:(NSData *)value
filename:(nullable NSString *)filename
extendedData:(nullable NSData *)extendedData;
#pragma mark - Remove Items
///=============================================================================
/// @name Remove Items
///=============================================================================
/**
Remove an item with 'key'.
@param key The item's key.
@return Whether succeed.
*/
- (BOOL)removeItemForKey:(NSString *)key;
/**
Remove items with an array of keys.
@param keys An array of specified keys.
@return Whether succeed.
*/
- (BOOL)removeItemForKeys:(NSArray<NSString *> *)keys;
/**
Remove all items which `value` is larger than a specified size.
@param size The maximum size in bytes.
@return Whether succeed.
*/
- (BOOL)removeItemsLargerThanSize:(int)size;
/**
Remove all items which last access time is earlier than a specified timestamp.
@param time The specified unix timestamp.
@return Whether succeed.
*/
- (BOOL)removeItemsEarlierThanTime:(int)time;
/**
Remove items to make the total size not larger than a specified size.
The least recently used (LRU) items will be removed first.
@param maxSize The specified size in bytes.
@return Whether succeed.
*/
- (BOOL)removeItemsToFitSize:(int)maxSize;
/**
Remove items to make the total count not larger than a specified count.
The least recently used (LRU) items will be removed first.
@param maxCount The specified item count.
@return Whether succeed.
*/
- (BOOL)removeItemsToFitCount:(int)maxCount;
/**
Remove all items in background queue.
@discussion This method will remove the files and sqlite database to a trash
folder, and then clear the folder in background queue. So this method is much
faster than `removeAllItemsWithProgressBlock:endBlock:`.
@return Whether succeed.
*/
- (BOOL)removeAllItems;
/**
Remove all items.
@warning You should not send message to this instance in these blocks.
@param progress This block will be invoked during removing, pass nil to ignore.
@param end This block will be invoked at the end, pass nil to ignore.
*/
- (void)removeAllItemsWithProgressBlock:(nullable void(^)(int removedCount, int totalCount))progress
endBlock:(nullable void(^)(BOOL error))end;
#pragma mark - Get Items
///=============================================================================
/// @name Get Items
///=============================================================================
/**
Get item with a specified key.
@param key A specified key.
@return Item for the key, or nil if not exists / error occurs.
*/
- (nullable YYKVStorageItem *)getItemForKey:(NSString *)key;
/**
Get item information with a specified key.
The `value` in this item will be ignored.
@param key A specified key.
@return Item information for the key, or nil if not exists / error occurs.
*/
- (nullable YYKVStorageItem *)getItemInfoForKey:(NSString *)key;
/**
Get item value with a specified key.
@param key A specified key.
@return Item's value, or nil if not exists / error occurs.
*/
- (nullable NSData *)getItemValueForKey:(NSString *)key;
/**
Get items with an array of keys.
@param keys An array of specified keys.
@return An array of `YYKVStorageItem`, or nil if not exists / error occurs.
*/
- (nullable NSArray<YYKVStorageItem *> *)getItemForKeys:(NSArray<NSString *> *)keys;
/**
Get item infomartions with an array of keys.
The `value` in items will be ignored.
@param keys An array of specified keys.
@return An array of `YYKVStorageItem`, or nil if not exists / error occurs.
*/
- (nullable NSArray<YYKVStorageItem *> *)getItemInfoForKeys:(NSArray<NSString *> *)keys;
/**
Get items value with an array of keys.
@param keys An array of specified keys.
@return A dictionary which key is 'key' and value is 'value', or nil if not
exists / error occurs.
*/
- (nullable NSDictionary<NSString *, NSData *> *)getItemValueForKeys:(NSArray<NSString *> *)keys;
#pragma mark - Get Storage Status
///=============================================================================
/// @name Get Storage Status
///=============================================================================
/**
Whether an item exists for a specified key.
@param key A specified key.
@return `YES` if there's an item exists for the key, `NO` if not exists or an error occurs.
*/
- (BOOL)itemExistsForKey:(NSString *)key;
/**
Get total item count.
@return Total item count, -1 when an error occurs.
*/
- (int)getItemsCount;
/**
Get item value's total size in bytes.
@return Total size in bytes, -1 when an error occurs.
*/
- (int)getItemsSize;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Cache/YYKVStorage.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 2,420
|
```objective-c
//
// YYMemoryCache.h
// YYKit <path_to_url
//
// Created by ibireme on 15/2/7.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
YYMemoryCache is a fast in-memory cache that stores key-value pairs.
In contrast to NSDictionary, keys are retained and not copied.
The API and performance is similar to `NSCache`, all methods are thread-safe.
YYMemoryCache objects differ from NSCache in a few ways:
* It uses LRU (least-recently-used) to remove objects; NSCache's eviction method
is non-deterministic.
* It can be controlled by cost, count and age; NSCache's limits are imprecise.
* It can be configured to automatically evict objects when receive memory
warning or app enter background.
The time of `Access Methods` in YYMemoryCache is typically in constant time (O(1)).
*/
@interface YYMemoryCache : NSObject
#pragma mark - Attribute
///=============================================================================
/// @name Attribute
///=============================================================================
/** The name of the cache. Default is nil. */
@property (nullable, copy) NSString *name;
/** The number of objects in the cache (read-only) */
@property (readonly) NSUInteger totalCount;
/** The total cost of objects in the cache (read-only). */
@property (readonly) NSUInteger totalCost;
#pragma mark - Limit
///=============================================================================
/// @name Limit
///=============================================================================
/**
The maximum number of objects the cache should hold.
@discussion The default value is NSUIntegerMax, which means no limit.
This is not a strict limitif the cache goes over the limit, some objects in the
cache could be evicted later in backgound thread.
*/
@property NSUInteger countLimit;
/**
The maximum total cost that the cache can hold before it starts evicting objects.
@discussion The default value is NSUIntegerMax, which means no limit.
This is not a strict limitif the cache goes over the limit, some objects in the
cache could be evicted later in backgound thread.
*/
@property NSUInteger costLimit;
/**
The maximum expiry time of objects in cache.
@discussion The default value is DBL_MAX, which means no limit.
This is not a strict limitif an object goes over the limit, the object could
be evicted later in backgound thread.
*/
@property NSTimeInterval ageLimit;
/**
The auto trim check time interval in seconds. Default is 5.0.
@discussion The cache holds an internal timer to check whether the cache reaches
its limits, and if the limit is reached, it begins to evict objects.
*/
@property NSTimeInterval autoTrimInterval;
/**
If `YES`, the cache will remove all objects when the app receives a memory warning.
The default value is `YES`.
*/
@property BOOL shouldRemoveAllObjectsOnMemoryWarning;
/**
If `YES`, The cache will remove all objects when the app enter background.
The default value is `YES`.
*/
@property BOOL shouldRemoveAllObjectsWhenEnteringBackground;
/**
A block to be executed when the app receives a memory warning.
The default value is nil.
*/
@property (nullable, copy) void(^didReceiveMemoryWarningBlock)(YYMemoryCache *cache);
/**
A block to be executed when the app enter background.
The default value is nil.
*/
@property (nullable, copy) void(^didEnterBackgroundBlock)(YYMemoryCache *cache);
/**
If `YES`, the key-value pair will be released on main thread, otherwise on
background thread. Default is NO.
@discussion You may set this value to `YES` if the key-value object contains
the instance which should be released in main thread (such as UIView/CALayer).
*/
@property BOOL releaseOnMainThread;
/**
If `YES`, the key-value pair will be released asynchronously to avoid blocking
the access methods, otherwise it will be released in the access method
(such as removeObjectForKey:). Default is YES.
*/
@property BOOL releaseAsynchronously;
#pragma mark - Access Methods
///=============================================================================
/// @name Access Methods
///=============================================================================
/**
Returns a Boolean value that indicates whether a given key is in cache.
@param key An object identifying the value. If nil, just return `NO`.
@return Whether the key is in cache.
*/
- (BOOL)containsObjectForKey:(id)key;
/**
Returns the value associated with a given key.
@param key An object identifying the value. If nil, just return nil.
@return The value associated with key, or nil if no value is associated with key.
*/
- (nullable id)objectForKey:(id)key;
/**
Sets the value of the specified key in the cache (0 cost).
@param object The object to be stored in the cache. If nil, it calls `removeObjectForKey:`.
@param key The key with which to associate the value. If nil, this method has no effect.
@discussion Unlike an NSMutableDictionary object, a cache does not copy the key
objects that are put into it.
*/
- (void)setObject:(nullable id)object forKey:(id)key;
/**
Sets the value of the specified key in the cache, and associates the key-value
pair with the specified cost.
@param object The object to store in the cache. If nil, it calls `removeObjectForKey`.
@param key The key with which to associate the value. If nil, this method has no effect.
@param cost The cost with which to associate the key-value pair.
@discussion Unlike an NSMutableDictionary object, a cache does not copy the key
objects that are put into it.
*/
- (void)setObject:(nullable id)object forKey:(id)key withCost:(NSUInteger)cost;
/**
Removes the value of the specified key in the cache.
@param key The key identifying the value to be removed. If nil, this method has no effect.
*/
- (void)removeObjectForKey:(id)key;
/**
Empties the cache immediately.
*/
- (void)removeAllObjects;
#pragma mark - Trim
///=============================================================================
/// @name Trim
///=============================================================================
/**
Removes objects from the cache with LRU, until the `totalCount` is below or equal to
the specified value.
@param count The total count allowed to remain after the cache has been trimmed.
*/
- (void)trimToCount:(NSUInteger)count;
/**
Removes objects from the cache with LRU, until the `totalCost` is or equal to
the specified value.
@param cost The total cost allowed to remain after the cache has been trimmed.
*/
- (void)trimToCost:(NSUInteger)cost;
/**
Removes objects from the cache with LRU, until all expiry objects removed by the
specified value.
@param age The maximum age (in seconds) of objects.
*/
- (void)trimToAge:(NSTimeInterval)age;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Cache/YYMemoryCache.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,456
|
```objective-c
//
// YYKitMacro.h
// YYKit <path_to_url
//
// Created by ibireme on 13/3/29.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
#import <sys/time.h>
#import <pthread.h>
#ifndef YYKitMacro_h
#define YYKitMacro_h
#ifdef __cplusplus
#define YY_EXTERN_C_BEGIN extern "C" {
#define YY_EXTERN_C_END }
#else
#define YY_EXTERN_C_BEGIN
#define YY_EXTERN_C_END
#endif
YY_EXTERN_C_BEGIN
#ifndef YY_CLAMP // return the clamped value
#define YY_CLAMP(_x_, _low_, _high_) (((_x_) > (_high_)) ? (_high_) : (((_x_) < (_low_)) ? (_low_) : (_x_)))
#endif
#ifndef YY_SWAP // swap two value
#define YY_SWAP(_a_, _b_) do { __typeof__(_a_) _tmp_ = (_a_); (_a_) = (_b_); (_b_) = _tmp_; } while (0)
#endif
#define YYAssertNil(condition, description, ...) NSAssert(!(condition), (description), ##__VA_ARGS__)
#define YYCAssertNil(condition, description, ...) NSCAssert(!(condition), (description), ##__VA_ARGS__)
#define YYAssertNotNil(condition, description, ...) NSAssert((condition), (description), ##__VA_ARGS__)
#define YYCAssertNotNil(condition, description, ...) NSCAssert((condition), (description), ##__VA_ARGS__)
#define YYAssertMainThread() NSAssert([NSThread isMainThread], @"This method must be called on the main thread")
#define YYCAssertMainThread() NSCAssert([NSThread isMainThread], @"This method must be called on the main thread")
/**
Add this macro before each category implementation, so we don't have to use
-all_load or -force_load to load object files from static libraries that only
contain categories and no classes.
More info: path_to_url#qa/qa2006/qa1490.html .
*******************************************************************************
Example:
YYSYNTH_DUMMY_CLASS(NSString_YYAdd)
*/
#ifndef YYSYNTH_DUMMY_CLASS
#define YYSYNTH_DUMMY_CLASS(_name_) \
@interface YYSYNTH_DUMMY_CLASS_ ## _name_ : NSObject @end \
@implementation YYSYNTH_DUMMY_CLASS_ ## _name_ @end
#endif
/**
Synthsize a dynamic object property in @implementation scope.
It allows us to add custom properties to existing classes in categories.
@param association ASSIGN / RETAIN / COPY / RETAIN_NONATOMIC / COPY_NONATOMIC
@warning #import <objc/runtime.h>
*******************************************************************************
Example:
@interface NSObject (MyAdd)
@property (nonatomic, retain) UIColor *myColor;
@end
#import <objc/runtime.h>
@implementation NSObject (MyAdd)
YYSYNTH_DYNAMIC_PROPERTY_OBJECT(myColor, setMyColor, RETAIN, UIColor *)
@end
*/
#ifndef YYSYNTH_DYNAMIC_PROPERTY_OBJECT
#define YYSYNTH_DYNAMIC_PROPERTY_OBJECT(_getter_, _setter_, _association_, _type_) \
- (void)_setter_ : (_type_)object { \
[self willChangeValueForKey:@#_getter_]; \
objc_setAssociatedObject(self, _cmd, object, OBJC_ASSOCIATION_ ## _association_); \
[self didChangeValueForKey:@#_getter_]; \
} \
- (_type_)_getter_ { \
return objc_getAssociatedObject(self, @selector(_setter_:)); \
}
#endif
/**
Synthsize a dynamic c type property in @implementation scope.
It allows us to add custom properties to existing classes in categories.
@warning #import <objc/runtime.h>
*******************************************************************************
Example:
@interface NSObject (MyAdd)
@property (nonatomic, retain) CGPoint myPoint;
@end
#import <objc/runtime.h>
@implementation NSObject (MyAdd)
YYSYNTH_DYNAMIC_PROPERTY_CTYPE(myPoint, setMyPoint, CGPoint)
@end
*/
#ifndef YYSYNTH_DYNAMIC_PROPERTY_CTYPE
#define YYSYNTH_DYNAMIC_PROPERTY_CTYPE(_getter_, _setter_, _type_) \
- (void)_setter_ : (_type_)object { \
[self willChangeValueForKey:@#_getter_]; \
NSValue *value = [NSValue value:&object withObjCType:@encode(_type_)]; \
objc_setAssociatedObject(self, _cmd, value, OBJC_ASSOCIATION_RETAIN); \
[self didChangeValueForKey:@#_getter_]; \
} \
- (_type_)_getter_ { \
_type_ cValue = { 0 }; \
NSValue *value = objc_getAssociatedObject(self, @selector(_setter_:)); \
[value getValue:&cValue]; \
return cValue; \
}
#endif
/**
Synthsize a weak or strong reference.
Example:
@weakify(self)
[self doSomething^{
@strongify(self)
if (!self) return;
...
}];
*/
#ifndef weakify
#if DEBUG
#if __has_feature(objc_arc)
#define weakify(object) autoreleasepool{} __weak __typeof__(object) weak##_##object = object;
#else
#define weakify(object) autoreleasepool{} __block __typeof__(object) block##_##object = object;
#endif
#else
#if __has_feature(objc_arc)
#define weakify(object) try{} @finally{} {} __weak __typeof__(object) weak##_##object = object;
#else
#define weakify(object) try{} @finally{} {} __block __typeof__(object) block##_##object = object;
#endif
#endif
#endif
#ifndef strongify
#if DEBUG
#if __has_feature(objc_arc)
#define strongify(object) autoreleasepool{} __typeof__(object) object = weak##_##object;
#else
#define strongify(object) autoreleasepool{} __typeof__(object) object = block##_##object;
#endif
#else
#if __has_feature(objc_arc)
#define strongify(object) try{} @finally{} __typeof__(object) object = weak##_##object;
#else
#define strongify(object) try{} @finally{} __typeof__(object) object = block##_##object;
#endif
#endif
#endif
/**
Convert CFRange to NSRange
@param range CFRange @return NSRange
*/
static inline NSRange YYNSRangeFromCFRange(CFRange range) {
return NSMakeRange(range.location, range.length);
}
/**
Convert NSRange to CFRange
@param range NSRange @return CFRange
*/
static inline CFRange YYCFRangeFromNSRange(NSRange range) {
return CFRangeMake(range.location, range.length);
}
/**
Same as CFAutorelease(), compatible for iOS6
@param arg CFObject @return same as input
*/
static inline CFTypeRef YYCFAutorelease(CFTypeRef CF_RELEASES_ARGUMENT arg) {
if (((long)CFAutorelease + 1) != 1) {
return CFAutorelease(arg);
} else {
id __autoreleasing obj = CFBridgingRelease(arg);
return (__bridge CFTypeRef)obj;
}
}
/**
Profile time cost.
@param ^block code to benchmark
@param ^complete code time cost (millisecond)
Usage:
YYBenchmark(^{
// code
}, ^(double ms) {
NSLog("time cost: %.2f ms",ms);
});
*/
static inline void YYBenchmark(void (^block)(void), void (^complete)(double ms)) {
// <QuartzCore/QuartzCore.h> version
/*
extern double CACurrentMediaTime (void);
double begin, end, ms;
begin = CACurrentMediaTime();
block();
end = CACurrentMediaTime();
ms = (end - begin) * 1000.0;
complete(ms);
*/
// <sys/time.h> version
struct timeval t0, t1;
gettimeofday(&t0, NULL);
block();
gettimeofday(&t1, NULL);
double ms = (double)(t1.tv_sec - t0.tv_sec) * 1e3 + (double)(t1.tv_usec - t0.tv_usec) * 1e-3;
complete(ms);
}
static inline NSDate *_YYCompileTime(const char *data, const char *time) {
NSString *timeStr = [NSString stringWithFormat:@"%s %s",data,time];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMM dd yyyy HH:mm:ss"];
[formatter setLocale:locale];
return [formatter dateFromString:timeStr];
}
/**
Get compile timestamp.
@return A new date object set to the compile date and time.
*/
#ifndef YYCompileTime
// use macro to avoid compile warning when use pch file
#define YYCompileTime() _YYCompileTime(__DATE__, __TIME__)
#endif
/**
Returns a dispatch_time delay from now.
*/
static inline dispatch_time_t dispatch_time_delay(NSTimeInterval second) {
return dispatch_time(DISPATCH_TIME_NOW, (int64_t)(second * NSEC_PER_SEC));
}
/**
Returns a dispatch_wall_time delay from now.
*/
static inline dispatch_time_t dispatch_walltime_delay(NSTimeInterval second) {
return dispatch_walltime(DISPATCH_TIME_NOW, (int64_t)(second * NSEC_PER_SEC));
}
/**
Returns a dispatch_wall_time from NSDate.
*/
static inline dispatch_time_t dispatch_walltime_date(NSDate *date) {
NSTimeInterval interval;
double second, subsecond;
struct timespec time;
dispatch_time_t milestone;
interval = [date timeIntervalSince1970];
subsecond = modf(interval, &second);
time.tv_sec = second;
time.tv_nsec = subsecond * NSEC_PER_SEC;
milestone = dispatch_walltime(&time, 0);
return milestone;
}
/**
Whether in main queue/thread.
*/
static inline bool dispatch_is_main_queue() {
return pthread_main_np() != 0;
}
/**
Submits a block for asynchronous execution on a main queue and returns immediately.
*/
static inline void dispatch_async_on_main_queue(void (^block)()) {
if (pthread_main_np()) {
block();
} else {
dispatch_async(dispatch_get_main_queue(), block);
}
}
/**
Submits a block for execution on a main queue and waits until the block completes.
*/
static inline void dispatch_sync_on_main_queue(void (^block)()) {
if (pthread_main_np()) {
block();
} else {
dispatch_sync(dispatch_get_main_queue(), block);
}
}
/**
Initialize a pthread mutex.
*/
static inline void pthread_mutex_init_recursive(pthread_mutex_t *mutex, bool recursive) {
#define YYMUTEX_ASSERT_ON_ERROR(x_) do { \
__unused volatile int res = (x_); \
assert(res == 0); \
} while (0)
assert(mutex != NULL);
if (!recursive) {
YYMUTEX_ASSERT_ON_ERROR(pthread_mutex_init(mutex, NULL));
} else {
pthread_mutexattr_t attr;
YYMUTEX_ASSERT_ON_ERROR(pthread_mutexattr_init (&attr));
YYMUTEX_ASSERT_ON_ERROR(pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE));
YYMUTEX_ASSERT_ON_ERROR(pthread_mutex_init (mutex, &attr));
YYMUTEX_ASSERT_ON_ERROR(pthread_mutexattr_destroy (&attr));
}
#undef YYMUTEX_ASSERT_ON_ERROR
}
YY_EXTERN_C_END
#endif
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/YYKitMacro.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 2,524
|
```objective-c
//
// YYKVStorage.m
// YYKit <path_to_url
//
// Created by ibireme on 15/4/22.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "YYKVStorage.h"
#import "UIApplication+YYAdd.h"
#import <UIKit/UIKit.h>
#import <time.h>
#if __has_include(<sqlite3.h>)
#import <sqlite3.h>
#else
#import "sqlite3.h"
#endif
static const NSUInteger kMaxErrorRetryCount = 8;
static const NSTimeInterval kMinRetryTimeInterval = 2.0;
static const int kPathLengthMax = PATH_MAX - 64;
static NSString *const kDBFileName = @"manifest.sqlite";
static NSString *const kDBShmFileName = @"manifest.sqlite-shm";
static NSString *const kDBWalFileName = @"manifest.sqlite-wal";
static NSString *const kDataDirectoryName = @"data";
static NSString *const kTrashDirectoryName = @"trash";
/*
File:
/path/
/manifest.sqlite
/manifest.sqlite-shm
/manifest.sqlite-wal
/data/
/e10adc3949ba59abbe56e057f20f883e
/e10adc3949ba59abbe56e057f20f883e
/trash/
/unused_file_or_folder
SQL:
create table if not exists manifest (
key text,
filename text,
size integer,
inline_data blob,
modification_time integer,
last_access_time integer,
extended_data blob,
primary key(key)
);
create index if not exists last_access_time_idx on manifest(last_access_time);
*/
@implementation YYKVStorageItem
@end
@implementation YYKVStorage {
dispatch_queue_t _trashQueue;
NSString *_path;
NSString *_dbPath;
NSString *_dataPath;
NSString *_trashPath;
sqlite3 *_db;
CFMutableDictionaryRef _dbStmtCache;
NSTimeInterval _dbLastOpenErrorTime;
NSUInteger _dbOpenErrorCount;
}
#pragma mark - db
- (BOOL)_dbOpen {
if (_db) return YES;
int result = sqlite3_open(_dbPath.UTF8String, &_db);
if (result == SQLITE_OK) {
CFDictionaryKeyCallBacks keyCallbacks = kCFCopyStringDictionaryKeyCallBacks;
CFDictionaryValueCallBacks valueCallbacks = {0};
_dbStmtCache = CFDictionaryCreateMutable(CFAllocatorGetDefault(), 0, &keyCallbacks, &valueCallbacks);
_dbLastOpenErrorTime = 0;
_dbOpenErrorCount = 0;
return YES;
} else {
_db = NULL;
if (_dbStmtCache) CFRelease(_dbStmtCache);
_dbStmtCache = NULL;
_dbLastOpenErrorTime = CACurrentMediaTime();
_dbOpenErrorCount++;
if (_errorLogsEnabled) {
NSLog(@"%s line:%d sqlite open failed (%d).", __FUNCTION__, __LINE__, result);
}
return NO;
}
}
- (BOOL)_dbClose {
if (!_db) return YES;
int result = 0;
BOOL retry = NO;
BOOL stmtFinalized = NO;
if (_dbStmtCache) CFRelease(_dbStmtCache);
_dbStmtCache = NULL;
do {
retry = NO;
result = sqlite3_close(_db);
if (result == SQLITE_BUSY || result == SQLITE_LOCKED) {
if (!stmtFinalized) {
stmtFinalized = YES;
sqlite3_stmt *stmt;
while ((stmt = sqlite3_next_stmt(_db, nil)) != 0) {
sqlite3_finalize(stmt);
retry = YES;
}
}
} else if (result != SQLITE_OK) {
if (_errorLogsEnabled) {
NSLog(@"%s line:%d sqlite close failed (%d).", __FUNCTION__, __LINE__, result);
}
}
} while (retry);
_db = NULL;
return YES;
}
- (BOOL)_dbCheck {
if (!_db) {
if (_dbOpenErrorCount < kMaxErrorRetryCount &&
CACurrentMediaTime() - _dbLastOpenErrorTime > kMinRetryTimeInterval) {
return [self _dbOpen] && [self _dbInitialize];
} else {
return NO;
}
}
return YES;
}
- (BOOL)_dbInitialize {
NSString *sql = @"pragma journal_mode = wal; pragma synchronous = normal; create table if not exists manifest (key text, filename text, size integer, inline_data blob, modification_time integer, last_access_time integer, extended_data blob, primary key(key)); create index if not exists last_access_time_idx on manifest(last_access_time);";
return [self _dbExecute:sql];
}
- (void)_dbCheckpoint {
if (![self _dbCheck]) return;
// Cause a checkpoint to occur, merge `sqlite-wal` file to `sqlite` file.
sqlite3_wal_checkpoint(_db, NULL);
}
- (BOOL)_dbExecute:(NSString *)sql {
if (sql.length == 0) return NO;
if (![self _dbCheck]) return NO;
char *error = NULL;
int result = sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &error);
if (error) {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite exec error (%d): %s", __FUNCTION__, __LINE__, result, error);
sqlite3_free(error);
}
return result == SQLITE_OK;
}
- (sqlite3_stmt *)_dbPrepareStmt:(NSString *)sql {
if (![self _dbCheck] || sql.length == 0 || !_dbStmtCache) return NULL;
sqlite3_stmt *stmt = (sqlite3_stmt *)CFDictionaryGetValue(_dbStmtCache, (__bridge const void *)(sql));
if (!stmt) {
int result = sqlite3_prepare_v2(_db, sql.UTF8String, -1, &stmt, NULL);
if (result != SQLITE_OK) {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite stmt prepare error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
return NULL;
}
CFDictionarySetValue(_dbStmtCache, (__bridge const void *)(sql), stmt);
} else {
sqlite3_reset(stmt);
}
return stmt;
}
- (NSString *)_dbJoinedKeys:(NSArray *)keys {
NSMutableString *string = [NSMutableString new];
for (NSUInteger i = 0,max = keys.count; i < max; i++) {
[string appendString:@"?"];
if (i + 1 != max) {
[string appendString:@","];
}
}
return string;
}
- (void)_dbBindJoinedKeys:(NSArray *)keys stmt:(sqlite3_stmt *)stmt fromIndex:(int)index{
for (int i = 0, max = (int)keys.count; i < max; i++) {
NSString *key = keys[i];
sqlite3_bind_text(stmt, index + i, key.UTF8String, -1, NULL);
}
}
- (BOOL)_dbSaveWithKey:(NSString *)key value:(NSData *)value fileName:(NSString *)fileName extendedData:(NSData *)extendedData {
NSString *sql = @"insert or replace into manifest (key, filename, size, inline_data, modification_time, last_access_time, extended_data) values (?1, ?2, ?3, ?4, ?5, ?6, ?7);";
sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
if (!stmt) return NO;
int timestamp = (int)time(NULL);
sqlite3_bind_text(stmt, 1, key.UTF8String, -1, NULL);
sqlite3_bind_text(stmt, 2, fileName.UTF8String, -1, NULL);
sqlite3_bind_int(stmt, 3, (int)value.length);
if (fileName.length == 0) {
sqlite3_bind_blob(stmt, 4, value.bytes, (int)value.length, 0);
} else {
sqlite3_bind_blob(stmt, 4, NULL, 0, 0);
}
sqlite3_bind_int(stmt, 5, timestamp);
sqlite3_bind_int(stmt, 6, timestamp);
sqlite3_bind_blob(stmt, 7, extendedData.bytes, (int)extendedData.length, 0);
int result = sqlite3_step(stmt);
if (result != SQLITE_DONE) {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite insert error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
return NO;
}
return YES;
}
- (BOOL)_dbUpdateAccessTimeWithKey:(NSString *)key {
NSString *sql = @"update manifest set last_access_time = ?1 where key = ?2;";
sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
if (!stmt) return NO;
sqlite3_bind_int(stmt, 1, (int)time(NULL));
sqlite3_bind_text(stmt, 2, key.UTF8String, -1, NULL);
int result = sqlite3_step(stmt);
if (result != SQLITE_DONE) {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite update error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
return NO;
}
return YES;
}
- (BOOL)_dbUpdateAccessTimeWithKeys:(NSArray *)keys {
if (![self _dbCheck]) return NO;
int t = (int)time(NULL);
NSString *sql = [NSString stringWithFormat:@"update manifest set last_access_time = %d where key in (%@);", t, [self _dbJoinedKeys:keys]];
sqlite3_stmt *stmt = NULL;
int result = sqlite3_prepare_v2(_db, sql.UTF8String, -1, &stmt, NULL);
if (result != SQLITE_OK) {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite stmt prepare error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
return NO;
}
[self _dbBindJoinedKeys:keys stmt:stmt fromIndex:1];
result = sqlite3_step(stmt);
sqlite3_finalize(stmt);
if (result != SQLITE_DONE) {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite update error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
return NO;
}
return YES;
}
- (BOOL)_dbDeleteItemWithKey:(NSString *)key {
NSString *sql = @"delete from manifest where key = ?1;";
sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
if (!stmt) return NO;
sqlite3_bind_text(stmt, 1, key.UTF8String, -1, NULL);
int result = sqlite3_step(stmt);
if (result != SQLITE_DONE) {
if (_errorLogsEnabled) NSLog(@"%s line:%d db delete error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
return NO;
}
return YES;
}
- (BOOL)_dbDeleteItemWithKeys:(NSArray *)keys {
if (![self _dbCheck]) return NO;
NSString *sql = [NSString stringWithFormat:@"delete from manifest where key in (%@);", [self _dbJoinedKeys:keys]];
sqlite3_stmt *stmt = NULL;
int result = sqlite3_prepare_v2(_db, sql.UTF8String, -1, &stmt, NULL);
if (result != SQLITE_OK) {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite stmt prepare error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
return NO;
}
[self _dbBindJoinedKeys:keys stmt:stmt fromIndex:1];
result = sqlite3_step(stmt);
sqlite3_finalize(stmt);
if (result == SQLITE_ERROR) {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite delete error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
return NO;
}
return YES;
}
- (BOOL)_dbDeleteItemsWithSizeLargerThan:(int)size {
NSString *sql = @"delete from manifest where size > ?1;";
sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
if (!stmt) return NO;
sqlite3_bind_int(stmt, 1, size);
int result = sqlite3_step(stmt);
if (result != SQLITE_DONE) {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite delete error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
return NO;
}
return YES;
}
- (BOOL)_dbDeleteItemsWithTimeEarlierThan:(int)time {
NSString *sql = @"delete from manifest where last_access_time < ?1;";
sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
if (!stmt) return NO;
sqlite3_bind_int(stmt, 1, time);
int result = sqlite3_step(stmt);
if (result != SQLITE_DONE) {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite delete error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
return NO;
}
return YES;
}
- (YYKVStorageItem *)_dbGetItemFromStmt:(sqlite3_stmt *)stmt excludeInlineData:(BOOL)excludeInlineData {
int i = 0;
char *key = (char *)sqlite3_column_text(stmt, i++);
char *filename = (char *)sqlite3_column_text(stmt, i++);
int size = sqlite3_column_int(stmt, i++);
const void *inline_data = excludeInlineData ? NULL : sqlite3_column_blob(stmt, i);
int inline_data_bytes = excludeInlineData ? 0 : sqlite3_column_bytes(stmt, i++);
int modification_time = sqlite3_column_int(stmt, i++);
int last_access_time = sqlite3_column_int(stmt, i++);
const void *extended_data = sqlite3_column_blob(stmt, i);
int extended_data_bytes = sqlite3_column_bytes(stmt, i++);
YYKVStorageItem *item = [YYKVStorageItem new];
if (key) item.key = [NSString stringWithUTF8String:key];
if (filename && *filename != 0) item.filename = [NSString stringWithUTF8String:filename];
item.size = size;
if (inline_data_bytes > 0 && inline_data) item.value = [NSData dataWithBytes:inline_data length:inline_data_bytes];
item.modTime = modification_time;
item.accessTime = last_access_time;
if (extended_data_bytes > 0 && extended_data) item.extendedData = [NSData dataWithBytes:extended_data length:extended_data_bytes];
return item;
}
- (YYKVStorageItem *)_dbGetItemWithKey:(NSString *)key excludeInlineData:(BOOL)excludeInlineData {
NSString *sql = excludeInlineData ? @"select key, filename, size, modification_time, last_access_time, extended_data from manifest where key = ?1;" : @"select key, filename, size, inline_data, modification_time, last_access_time, extended_data from manifest where key = ?1;";
sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
if (!stmt) return nil;
sqlite3_bind_text(stmt, 1, key.UTF8String, -1, NULL);
YYKVStorageItem *item = nil;
int result = sqlite3_step(stmt);
if (result == SQLITE_ROW) {
item = [self _dbGetItemFromStmt:stmt excludeInlineData:excludeInlineData];
} else {
if (result != SQLITE_DONE) {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
}
}
return item;
}
- (NSMutableArray *)_dbGetItemWithKeys:(NSArray *)keys excludeInlineData:(BOOL)excludeInlineData {
if (![self _dbCheck]) return nil;
NSString *sql;
if (excludeInlineData) {
sql = [NSString stringWithFormat:@"select key, filename, size, modification_time, last_access_time, extended_data from manifest where key in (%@);", [self _dbJoinedKeys:keys]];
} else {
sql = [NSString stringWithFormat:@"select key, filename, size, inline_data, modification_time, last_access_time, extended_data from manifest where key in (%@)", [self _dbJoinedKeys:keys]];
}
sqlite3_stmt *stmt = NULL;
int result = sqlite3_prepare_v2(_db, sql.UTF8String, -1, &stmt, NULL);
if (result != SQLITE_OK) {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite stmt prepare error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
return nil;
}
[self _dbBindJoinedKeys:keys stmt:stmt fromIndex:1];
NSMutableArray *items = [NSMutableArray new];
do {
result = sqlite3_step(stmt);
if (result == SQLITE_ROW) {
YYKVStorageItem *item = [self _dbGetItemFromStmt:stmt excludeInlineData:excludeInlineData];
if (item) [items addObject:item];
} else if (result == SQLITE_DONE) {
break;
} else {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
items = nil;
break;
}
} while (1);
sqlite3_finalize(stmt);
return items;
}
- (NSData *)_dbGetValueWithKey:(NSString *)key {
NSString *sql = @"select inline_data from manifest where key = ?1;";
sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
if (!stmt) return nil;
sqlite3_bind_text(stmt, 1, key.UTF8String, -1, NULL);
int result = sqlite3_step(stmt);
if (result == SQLITE_ROW) {
const void *inline_data = sqlite3_column_blob(stmt, 0);
int inline_data_bytes = sqlite3_column_bytes(stmt, 0);
if (!inline_data || inline_data_bytes <= 0) return nil;
return [NSData dataWithBytes:inline_data length:inline_data_bytes];
} else {
if (result != SQLITE_DONE) {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
}
return nil;
}
}
- (NSString *)_dbGetFilenameWithKey:(NSString *)key {
NSString *sql = @"select filename from manifest where key = ?1;";
sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
if (!stmt) return nil;
sqlite3_bind_text(stmt, 1, key.UTF8String, -1, NULL);
int result = sqlite3_step(stmt);
if (result == SQLITE_ROW) {
char *filename = (char *)sqlite3_column_text(stmt, 0);
if (filename && *filename != 0) {
return [NSString stringWithUTF8String:filename];
}
} else {
if (result != SQLITE_DONE) {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
}
}
return nil;
}
- (NSMutableArray *)_dbGetFilenameWithKeys:(NSArray *)keys {
if (![self _dbCheck]) return nil;
NSString *sql = [NSString stringWithFormat:@"select filename from manifest where key in (%@);", [self _dbJoinedKeys:keys]];
sqlite3_stmt *stmt = NULL;
int result = sqlite3_prepare_v2(_db, sql.UTF8String, -1, &stmt, NULL);
if (result != SQLITE_OK) {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite stmt prepare error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
return nil;
}
[self _dbBindJoinedKeys:keys stmt:stmt fromIndex:1];
NSMutableArray *filenames = [NSMutableArray new];
do {
result = sqlite3_step(stmt);
if (result == SQLITE_ROW) {
char *filename = (char *)sqlite3_column_text(stmt, 0);
if (filename && *filename != 0) {
NSString *name = [NSString stringWithUTF8String:filename];
if (name) [filenames addObject:name];
}
} else if (result == SQLITE_DONE) {
break;
} else {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
filenames = nil;
break;
}
} while (1);
sqlite3_finalize(stmt);
return filenames;
}
- (NSMutableArray *)_dbGetFilenamesWithSizeLargerThan:(int)size {
NSString *sql = @"select filename from manifest where size > ?1 and filename is not null;";
sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
if (!stmt) return nil;
sqlite3_bind_int(stmt, 1, size);
NSMutableArray *filenames = [NSMutableArray new];
do {
int result = sqlite3_step(stmt);
if (result == SQLITE_ROW) {
char *filename = (char *)sqlite3_column_text(stmt, 0);
if (filename && *filename != 0) {
NSString *name = [NSString stringWithUTF8String:filename];
if (name) [filenames addObject:name];
}
} else if (result == SQLITE_DONE) {
break;
} else {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
filenames = nil;
break;
}
} while (1);
return filenames;
}
- (NSMutableArray *)_dbGetFilenamesWithTimeEarlierThan:(int)time {
NSString *sql = @"select filename from manifest where last_access_time < ?1 and filename is not null;";
sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
if (!stmt) return nil;
sqlite3_bind_int(stmt, 1, time);
NSMutableArray *filenames = [NSMutableArray new];
do {
int result = sqlite3_step(stmt);
if (result == SQLITE_ROW) {
char *filename = (char *)sqlite3_column_text(stmt, 0);
if (filename && *filename != 0) {
NSString *name = [NSString stringWithUTF8String:filename];
if (name) [filenames addObject:name];
}
} else if (result == SQLITE_DONE) {
break;
} else {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
filenames = nil;
break;
}
} while (1);
return filenames;
}
- (NSMutableArray *)_dbGetItemSizeInfoOrderByTimeAscWithLimit:(int)count {
NSString *sql = @"select key, filename, size from manifest order by last_access_time asc limit ?1;";
sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
if (!stmt) return nil;
sqlite3_bind_int(stmt, 1, count);
NSMutableArray *items = [NSMutableArray new];
do {
int result = sqlite3_step(stmt);
if (result == SQLITE_ROW) {
char *key = (char *)sqlite3_column_text(stmt, 0);
char *filename = (char *)sqlite3_column_text(stmt, 1);
int size = sqlite3_column_int(stmt, 2);
NSString *keyStr = key ? [NSString stringWithUTF8String:key] : nil;
if (keyStr) {
YYKVStorageItem *item = [YYKVStorageItem new];
item.key = key ? [NSString stringWithUTF8String:key] : nil;
item.filename = filename ? [NSString stringWithUTF8String:filename] : nil;
item.size = size;
[items addObject:item];
}
} else if (result == SQLITE_DONE) {
break;
} else {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
items = nil;
break;
}
} while (1);
return items;
}
- (int)_dbGetItemCountWithKey:(NSString *)key {
NSString *sql = @"select count(key) from manifest where key = ?1;";
sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
if (!stmt) return -1;
sqlite3_bind_text(stmt, 1, key.UTF8String, -1, NULL);
int result = sqlite3_step(stmt);
if (result != SQLITE_ROW) {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
return -1;
}
return sqlite3_column_int(stmt, 0);
}
- (int)_dbGetTotalItemSize {
NSString *sql = @"select sum(size) from manifest;";
sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
if (!stmt) return -1;
int result = sqlite3_step(stmt);
if (result != SQLITE_ROW) {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
return -1;
}
return sqlite3_column_int(stmt, 0);
}
- (int)_dbGetTotalItemCount {
NSString *sql = @"select count(*) from manifest;";
sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];
if (!stmt) return -1;
int result = sqlite3_step(stmt);
if (result != SQLITE_ROW) {
if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));
return -1;
}
return sqlite3_column_int(stmt, 0);
}
#pragma mark - file
- (BOOL)_fileWriteWithName:(NSString *)filename data:(NSData *)data {
NSString *path = [_dataPath stringByAppendingPathComponent:filename];
return [data writeToFile:path atomically:NO];
}
- (NSData *)_fileReadWithName:(NSString *)filename {
NSString *path = [_dataPath stringByAppendingPathComponent:filename];
NSData *data = [NSData dataWithContentsOfFile:path];
return data;
}
- (BOOL)_fileDeleteWithName:(NSString *)filename {
NSString *path = [_dataPath stringByAppendingPathComponent:filename];
return [[NSFileManager defaultManager] removeItemAtPath:path error:NULL];
}
- (BOOL)_fileMoveAllToTrash {
CFUUIDRef uuidRef = CFUUIDCreate(NULL);
CFStringRef uuid = CFUUIDCreateString(NULL, uuidRef);
CFRelease(uuidRef);
NSString *tmpPath = [_trashPath stringByAppendingPathComponent:(__bridge NSString *)(uuid)];
BOOL suc = [[NSFileManager defaultManager] moveItemAtPath:_dataPath toPath:tmpPath error:nil];
if (suc) {
suc = [[NSFileManager defaultManager] createDirectoryAtPath:_dataPath withIntermediateDirectories:YES attributes:nil error:NULL];
}
CFRelease(uuid);
return suc;
}
- (void)_fileEmptyTrashInBackground {
NSString *trashPath = _trashPath;
dispatch_queue_t queue = _trashQueue;
dispatch_async(queue, ^{
NSFileManager *manager = [NSFileManager new];
NSArray *directoryContents = [manager contentsOfDirectoryAtPath:trashPath error:NULL];
for (NSString *path in directoryContents) {
NSString *fullPath = [trashPath stringByAppendingPathComponent:path];
[manager removeItemAtPath:fullPath error:NULL];
}
});
}
#pragma mark - private
/**
Delete all files and empty in background.
Make sure the db is closed.
*/
- (void)_reset {
[[NSFileManager defaultManager] removeItemAtPath:[_path stringByAppendingPathComponent:kDBFileName] error:nil];
[[NSFileManager defaultManager] removeItemAtPath:[_path stringByAppendingPathComponent:kDBShmFileName] error:nil];
[[NSFileManager defaultManager] removeItemAtPath:[_path stringByAppendingPathComponent:kDBWalFileName] error:nil];
[self _fileMoveAllToTrash];
[self _fileEmptyTrashInBackground];
}
#pragma mark - public
- (instancetype)init {
@throw [NSException exceptionWithName:@"YYKVStorage init error" reason:@"Please use the designated initializer and pass the 'path' and 'type'." userInfo:nil];
return [self initWithPath:@"" type:YYKVStorageTypeFile];
}
- (instancetype)initWithPath:(NSString *)path type:(YYKVStorageType)type {
if (path.length == 0 || path.length > kPathLengthMax) {
NSLog(@"YYKVStorage init error: invalid path: [%@].", path);
return nil;
}
if (type > YYKVStorageTypeMixed) {
NSLog(@"YYKVStorage init error: invalid type: %lu.", (unsigned long)type);
return nil;
}
self = [super init];
_path = path.copy;
_type = type;
_dataPath = [path stringByAppendingPathComponent:kDataDirectoryName];
_trashPath = [path stringByAppendingPathComponent:kTrashDirectoryName];
_trashQueue = dispatch_queue_create("com.ibireme.cache.disk.trash", DISPATCH_QUEUE_SERIAL);
_dbPath = [path stringByAppendingPathComponent:kDBFileName];
_errorLogsEnabled = YES;
NSError *error = nil;
if (![[NSFileManager defaultManager] createDirectoryAtPath:path
withIntermediateDirectories:YES
attributes:nil
error:&error] ||
![[NSFileManager defaultManager] createDirectoryAtPath:[path stringByAppendingPathComponent:kDataDirectoryName]
withIntermediateDirectories:YES
attributes:nil
error:&error] ||
![[NSFileManager defaultManager] createDirectoryAtPath:[path stringByAppendingPathComponent:kTrashDirectoryName]
withIntermediateDirectories:YES
attributes:nil
error:&error]) {
NSLog(@"YYKVStorage init error:%@", error);
return nil;
}
if (![self _dbOpen] || ![self _dbInitialize]) {
// db file may broken...
[self _dbClose];
[self _reset]; // rebuild
if (![self _dbOpen] || ![self _dbInitialize]) {
[self _dbClose];
NSLog(@"YYKVStorage init error: fail to open sqlite db.");
return nil;
}
}
[self _fileEmptyTrashInBackground]; // empty the trash if failed at last time
return self;
}
- (void)dealloc {
UIBackgroundTaskIdentifier taskID = [[UIApplication sharedExtensionApplication] beginBackgroundTaskWithExpirationHandler:^{}];
[self _dbClose];
if (taskID != UIBackgroundTaskInvalid) {
[[UIApplication sharedExtensionApplication] endBackgroundTask:taskID];
}
}
- (BOOL)saveItem:(YYKVStorageItem *)item {
return [self saveItemWithKey:item.key value:item.value filename:item.filename extendedData:item.extendedData];
}
- (BOOL)saveItemWithKey:(NSString *)key value:(NSData *)value {
return [self saveItemWithKey:key value:value filename:nil extendedData:nil];
}
- (BOOL)saveItemWithKey:(NSString *)key value:(NSData *)value filename:(NSString *)filename extendedData:(NSData *)extendedData {
if (key.length == 0 || value.length == 0) return NO;
if (_type == YYKVStorageTypeFile && filename.length == 0) {
return NO;
}
if (filename.length) {
if (![self _fileWriteWithName:filename data:value]) {
return NO;
}
if (![self _dbSaveWithKey:key value:value fileName:filename extendedData:extendedData]) {
[self _fileDeleteWithName:filename];
return NO;
}
return YES;
} else {
if (_type != YYKVStorageTypeSQLite) {
NSString *filename = [self _dbGetFilenameWithKey:key];
if (filename) {
[self _fileDeleteWithName:filename];
}
}
return [self _dbSaveWithKey:key value:value fileName:nil extendedData:extendedData];
}
}
- (BOOL)removeItemForKey:(NSString *)key {
if (key.length == 0) return NO;
switch (_type) {
case YYKVStorageTypeSQLite: {
return [self _dbDeleteItemWithKey:key];
} break;
case YYKVStorageTypeFile:
case YYKVStorageTypeMixed: {
NSString *filename = [self _dbGetFilenameWithKey:key];
if (filename) {
[self _fileDeleteWithName:filename];
}
return [self _dbDeleteItemWithKey:key];
} break;
default: return NO;
}
}
- (BOOL)removeItemForKeys:(NSArray *)keys {
if (keys.count == 0) return NO;
switch (_type) {
case YYKVStorageTypeSQLite: {
return [self _dbDeleteItemWithKeys:keys];
} break;
case YYKVStorageTypeFile:
case YYKVStorageTypeMixed: {
NSArray *filenames = [self _dbGetFilenameWithKeys:keys];
for (NSString *filename in filenames) {
[self _fileDeleteWithName:filename];
}
return [self _dbDeleteItemWithKeys:keys];
} break;
default: return NO;
}
}
- (BOOL)removeItemsLargerThanSize:(int)size {
if (size == INT_MAX) return YES;
if (size <= 0) return [self removeAllItems];
switch (_type) {
case YYKVStorageTypeSQLite: {
if ([self _dbDeleteItemsWithSizeLargerThan:size]) {
[self _dbCheckpoint];
return YES;
}
} break;
case YYKVStorageTypeFile:
case YYKVStorageTypeMixed: {
NSArray *filenames = [self _dbGetFilenamesWithSizeLargerThan:size];
for (NSString *name in filenames) {
[self _fileDeleteWithName:name];
}
if ([self _dbDeleteItemsWithSizeLargerThan:size]) {
[self _dbCheckpoint];
return YES;
}
} break;
}
return NO;
}
- (BOOL)removeItemsEarlierThanTime:(int)time {
if (time <= 0) return YES;
if (time == INT_MAX) return [self removeAllItems];
switch (_type) {
case YYKVStorageTypeSQLite: {
if ([self _dbDeleteItemsWithTimeEarlierThan:time]) {
[self _dbCheckpoint];
return YES;
}
} break;
case YYKVStorageTypeFile:
case YYKVStorageTypeMixed: {
NSArray *filenames = [self _dbGetFilenamesWithTimeEarlierThan:time];
for (NSString *name in filenames) {
[self _fileDeleteWithName:name];
}
if ([self _dbDeleteItemsWithTimeEarlierThan:time]) {
[self _dbCheckpoint];
return YES;
}
} break;
}
return NO;
}
- (BOOL)removeItemsToFitSize:(int)maxSize {
if (maxSize == INT_MAX) return YES;
if (maxSize <= 0) return [self removeAllItems];
int total = [self _dbGetTotalItemSize];
if (total < 0) return NO;
if (total <= maxSize) return YES;
NSArray *items = nil;
BOOL suc = NO;
do {
int perCount = 16;
items = [self _dbGetItemSizeInfoOrderByTimeAscWithLimit:perCount];
for (YYKVStorageItem *item in items) {
if (total > maxSize) {
if (item.filename) {
[self _fileDeleteWithName:item.filename];
}
suc = [self _dbDeleteItemWithKey:item.key];
total -= item.size;
} else {
break;
}
if (!suc) break;
}
} while (total > maxSize && items.count > 0 && suc);
if (suc) [self _dbCheckpoint];
return suc;
}
- (BOOL)removeItemsToFitCount:(int)maxCount {
if (maxCount == INT_MAX) return YES;
if (maxCount <= 0) return [self removeAllItems];
int total = [self _dbGetTotalItemCount];
if (total < 0) return NO;
if (total <= maxCount) return YES;
NSArray *items = nil;
BOOL suc = NO;
do {
int perCount = 16;
items = [self _dbGetItemSizeInfoOrderByTimeAscWithLimit:perCount];
for (YYKVStorageItem *item in items) {
if (total > maxCount) {
if (item.filename) {
[self _fileDeleteWithName:item.filename];
}
suc = [self _dbDeleteItemWithKey:item.key];
total--;
} else {
break;
}
if (!suc) break;
}
} while (total > maxCount && items.count > 0 && suc);
if (suc) [self _dbCheckpoint];
return suc;
}
- (BOOL)removeAllItems {
if (![self _dbClose]) return NO;
[self _reset];
if (![self _dbOpen]) return NO;
if (![self _dbInitialize]) return NO;
return YES;
}
- (void)removeAllItemsWithProgressBlock:(void(^)(int removedCount, int totalCount))progress
endBlock:(void(^)(BOOL error))end {
int total = [self _dbGetTotalItemCount];
if (total <= 0) {
if (end) end(total < 0);
} else {
int left = total;
int perCount = 32;
NSArray *items = nil;
BOOL suc = NO;
do {
items = [self _dbGetItemSizeInfoOrderByTimeAscWithLimit:perCount];
for (YYKVStorageItem *item in items) {
if (left > 0) {
if (item.filename) {
[self _fileDeleteWithName:item.filename];
}
suc = [self _dbDeleteItemWithKey:item.key];
left--;
} else {
break;
}
if (!suc) break;
}
if (progress) progress(total - left, total);
} while (left > 0 && items.count > 0 && suc);
if (suc) [self _dbCheckpoint];
if (end) end(!suc);
}
}
- (YYKVStorageItem *)getItemForKey:(NSString *)key {
if (key.length == 0) return nil;
YYKVStorageItem *item = [self _dbGetItemWithKey:key excludeInlineData:NO];
if (item) {
[self _dbUpdateAccessTimeWithKey:key];
if (item.filename) {
item.value = [self _fileReadWithName:item.filename];
if (!item.value) {
[self _dbDeleteItemWithKey:key];
item = nil;
}
}
}
return item;
}
- (YYKVStorageItem *)getItemInfoForKey:(NSString *)key {
if (key.length == 0) return nil;
YYKVStorageItem *item = [self _dbGetItemWithKey:key excludeInlineData:YES];
return item;
}
- (NSData *)getItemValueForKey:(NSString *)key {
if (key.length == 0) return nil;
NSData *value = nil;
switch (_type) {
case YYKVStorageTypeFile: {
NSString *filename = [self _dbGetFilenameWithKey:key];
if (filename) {
value = [self _fileReadWithName:filename];
if (!value) {
[self _dbDeleteItemWithKey:key];
value = nil;
}
}
} break;
case YYKVStorageTypeSQLite: {
value = [self _dbGetValueWithKey:key];
} break;
case YYKVStorageTypeMixed: {
NSString *filename = [self _dbGetFilenameWithKey:key];
if (filename) {
value = [self _fileReadWithName:filename];
if (!value) {
[self _dbDeleteItemWithKey:key];
value = nil;
}
} else {
value = [self _dbGetValueWithKey:key];
}
} break;
}
if (value) {
[self _dbUpdateAccessTimeWithKey:key];
}
return value;
}
- (NSArray *)getItemForKeys:(NSArray *)keys {
if (keys.count == 0) return nil;
NSMutableArray *items = [self _dbGetItemWithKeys:keys excludeInlineData:NO];
if (_type != YYKVStorageTypeSQLite) {
for (NSInteger i = 0, max = items.count; i < max; i++) {
YYKVStorageItem *item = items[i];
if (item.filename) {
item.value = [self _fileReadWithName:item.filename];
if (!item.value) {
if (item.key) [self _dbDeleteItemWithKey:item.key];
[items removeObjectAtIndex:i];
i--;
max--;
}
}
}
}
if (items.count > 0) {
[self _dbUpdateAccessTimeWithKeys:keys];
}
return items.count ? items : nil;
}
- (NSArray *)getItemInfoForKeys:(NSArray *)keys {
if (keys.count == 0) return nil;
return [self _dbGetItemWithKeys:keys excludeInlineData:YES];
}
- (NSDictionary *)getItemValueForKeys:(NSArray *)keys {
NSMutableArray *items = (NSMutableArray *)[self getItemForKeys:keys];
NSMutableDictionary *kv = [NSMutableDictionary new];
for (YYKVStorageItem *item in items) {
if (item.key && item.value) {
[kv setObject:item.value forKey:item.key];
}
}
return kv.count ? kv : nil;
}
- (BOOL)itemExistsForKey:(NSString *)key {
if (key.length == 0) return NO;
return [self _dbGetItemCountWithKey:key] > 0;
}
- (int)getItemsCount {
return [self _dbGetTotalItemCount];
}
- (int)getItemsSize {
return [self _dbGetTotalItemSize];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Cache/YYKVStorage.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 9,408
|
```objective-c
//
// CALayer+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 14/5/10.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "CALayer+YYAdd.h"
#import "YYKitMacro.h"
#import "YYCGUtilities.h"
YYSYNTH_DUMMY_CLASS(CALayer_YYAdd)
@implementation CALayer (YYAdd)
- (UIImage *)snapshotImage {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
[self renderInContext:context];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
- (NSData *)snapshotPDF {
CGRect bounds = self.bounds;
NSMutableData *data = [NSMutableData data];
CGDataConsumerRef consumer = CGDataConsumerCreateWithCFData((__bridge CFMutableDataRef)data);
CGContextRef context = CGPDFContextCreate(consumer, &bounds, NULL);
CGDataConsumerRelease(consumer);
if (!context) return nil;
CGPDFContextBeginPage(context, NULL);
CGContextTranslateCTM(context, 0, bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
[self renderInContext:context];
CGPDFContextEndPage(context);
CGPDFContextClose(context);
CGContextRelease(context);
return data;
}
- (void)setLayerShadow:(UIColor*)color offset:(CGSize)offset radius:(CGFloat)radius {
self.shadowColor = color.CGColor;
self.shadowOffset = offset;
self.shadowRadius = radius;
self.shadowOpacity = 1;
self.shouldRasterize = YES;
self.rasterizationScale = [UIScreen mainScreen].scale;
}
- (void)removeAllSublayers {
while (self.sublayers.count) {
[self.sublayers.lastObject removeFromSuperlayer];
}
}
- (CGFloat)left {
return self.frame.origin.x;
}
- (void)setLeft:(CGFloat)x {
CGRect frame = self.frame;
frame.origin.x = x;
self.frame = frame;
}
- (CGFloat)top {
return self.frame.origin.y;
}
- (void)setTop:(CGFloat)y {
CGRect frame = self.frame;
frame.origin.y = y;
self.frame = frame;
}
- (CGFloat)right {
return self.frame.origin.x + self.frame.size.width;
}
- (void)setRight:(CGFloat)right {
CGRect frame = self.frame;
frame.origin.x = right - frame.size.width;
self.frame = frame;
}
- (CGFloat)bottom {
return self.frame.origin.y + self.frame.size.height;
}
- (void)setBottom:(CGFloat)bottom {
CGRect frame = self.frame;
frame.origin.y = bottom - frame.size.height;
self.frame = frame;
}
- (CGFloat)width {
return self.frame.size.width;
}
- (void)setWidth:(CGFloat)width {
CGRect frame = self.frame;
frame.size.width = width;
self.frame = frame;
}
- (CGFloat)height {
return self.frame.size.height;
}
- (void)setHeight:(CGFloat)height {
CGRect frame = self.frame;
frame.size.height = height;
self.frame = frame;
}
- (CGPoint)center {
return CGPointMake(self.frame.origin.x + self.frame.size.width * 0.5,
self.frame.origin.y + self.frame.size.height * 0.5);
}
- (void)setCenter:(CGPoint)center {
CGRect frame = self.frame;
frame.origin.x = center.x - frame.size.width * 0.5;
frame.origin.y = center.y - frame.size.height * 0.5;
self.frame = frame;
}
- (CGFloat)centerX {
return self.frame.origin.x + self.frame.size.width * 0.5;
}
- (void)setCenterX:(CGFloat)centerX {
CGRect frame = self.frame;
frame.origin.x = centerX - frame.size.width * 0.5;
self.frame = frame;
}
- (CGFloat)centerY {
return self.frame.origin.y + self.frame.size.height * 0.5;
}
- (void)setCenterY:(CGFloat)centerY {
CGRect frame = self.frame;
frame.origin.y = centerY - frame.size.height * 0.5;
self.frame = frame;
}
- (CGPoint)origin {
return self.frame.origin;
}
- (void)setOrigin:(CGPoint)origin {
CGRect frame = self.frame;
frame.origin = origin;
self.frame = frame;
}
- (CGSize)frameSize {
return self.frame.size;
}
- (void)setFrameSize:(CGSize)size {
CGRect frame = self.frame;
frame.size = size;
self.frame = frame;
}
- (CGFloat)transformRotation {
NSNumber *v = [self valueForKeyPath:@"transform.rotation"];
return v.doubleValue;
}
- (void)setTransformRotation:(CGFloat)v {
[self setValue:@(v) forKeyPath:@"transform.rotation"];
}
- (CGFloat)transformRotationX {
NSNumber *v = [self valueForKeyPath:@"transform.rotation.x"];
return v.doubleValue;
}
- (void)setTransformRotationX:(CGFloat)v {
[self setValue:@(v) forKeyPath:@"transform.rotation.x"];
}
- (CGFloat)transformRotationY {
NSNumber *v = [self valueForKeyPath:@"transform.rotation.y"];
return v.doubleValue;
}
- (void)setTransformRotationY:(CGFloat)v {
[self setValue:@(v) forKeyPath:@"transform.rotation.y"];
}
- (CGFloat)transformRotationZ {
NSNumber *v = [self valueForKeyPath:@"transform.rotation.z"];
return v.doubleValue;
}
- (void)setTransformRotationZ:(CGFloat)v {
[self setValue:@(v) forKeyPath:@"transform.rotation.z"];
}
- (CGFloat)transformScaleX {
NSNumber *v = [self valueForKeyPath:@"transform.scale.x"];
return v.doubleValue;
}
- (void)setTransformScaleX:(CGFloat)v {
[self setValue:@(v) forKeyPath:@"transform.scale.x"];
}
- (CGFloat)transformScaleY {
NSNumber *v = [self valueForKeyPath:@"transform.scale.y"];
return v.doubleValue;
}
- (void)setTransformScaleY:(CGFloat)v {
[self setValue:@(v) forKeyPath:@"transform.scale.y"];
}
- (CGFloat)transformScaleZ {
NSNumber *v = [self valueForKeyPath:@"transform.scale.z"];
return v.doubleValue;
}
- (void)setTransformScaleZ:(CGFloat)v {
[self setValue:@(v) forKeyPath:@"transform.scale.z"];
}
- (CGFloat)transformScale {
NSNumber *v = [self valueForKeyPath:@"transform.scale"];
return v.doubleValue;
}
- (void)setTransformScale:(CGFloat)v {
[self setValue:@(v) forKeyPath:@"transform.scale"];
}
- (CGFloat)transformTranslationX {
NSNumber *v = [self valueForKeyPath:@"transform.translation.x"];
return v.doubleValue;
}
- (void)setTransformTranslationX:(CGFloat)v {
[self setValue:@(v) forKeyPath:@"transform.translation.x"];
}
- (CGFloat)transformTranslationY {
NSNumber *v = [self valueForKeyPath:@"transform.translation.y"];
return v.doubleValue;
}
- (void)setTransformTranslationY:(CGFloat)v {
[self setValue:@(v) forKeyPath:@"transform.translation.y"];
}
- (CGFloat)transformTranslationZ {
NSNumber *v = [self valueForKeyPath:@"transform.translation.z"];
return v.doubleValue;
}
- (void)setTransformTranslationZ:(CGFloat)v {
[self setValue:@(v) forKeyPath:@"transform.translation.z"];
}
- (CGFloat)transformDepth {
return self.transform.m34;
}
- (void)setTransformDepth:(CGFloat)v {
CATransform3D d = self.transform;
d.m34 = v;
self.transform = d;
}
- (UIViewContentMode)contentMode {
return YYCAGravityToUIViewContentMode(self.contentsGravity);
}
- (void)setContentMode:(UIViewContentMode)contentMode {
self.contentsGravity = YYUIViewContentModeToCAGravity(contentMode);
}
- (void)addFadeAnimationWithDuration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
if (duration <= 0) return;
NSString *mediaFunction;
switch (curve) {
case UIViewAnimationCurveEaseInOut: {
mediaFunction = kCAMediaTimingFunctionEaseInEaseOut;
} break;
case UIViewAnimationCurveEaseIn: {
mediaFunction = kCAMediaTimingFunctionEaseIn;
} break;
case UIViewAnimationCurveEaseOut: {
mediaFunction = kCAMediaTimingFunctionEaseOut;
} break;
case UIViewAnimationCurveLinear: {
mediaFunction = kCAMediaTimingFunctionLinear;
} break;
default: {
mediaFunction = kCAMediaTimingFunctionLinear;
} break;
}
CATransition *transition = [CATransition animation];
transition.duration = duration;
transition.timingFunction = [CAMediaTimingFunction functionWithName:mediaFunction];
transition.type = kCATransitionFade;
[self addAnimation:transition forKey:@"yykit.fade"];
}
- (void)removePreviousFadeAnimation {
[self removeAnimationForKey:@"yykit.fade"];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Quartz/CALayer+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 2,000
|
```objective-c
//
// CALayer+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 14/5/10.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provides extensions for `CALayer`.
*/
@interface CALayer (YYAdd)
/**
Take snapshot without transform, image's size equals to bounds.
*/
- (nullable UIImage *)snapshotImage;
/**
Take snapshot without transform, PDF's page size equals to bounds.
*/
- (nullable NSData *)snapshotPDF;
/**
Shortcut to set the layer's shadow
@param color Shadow Color
@param offset Shadow offset
@param radius Shadow radius
*/
- (void)setLayerShadow:(UIColor*)color offset:(CGSize)offset radius:(CGFloat)radius;
/**
Remove all sublayers.
*/
- (void)removeAllSublayers;
@property (nonatomic) CGFloat left; ///< Shortcut for frame.origin.x.
@property (nonatomic) CGFloat top; ///< Shortcut for frame.origin.y
@property (nonatomic) CGFloat right; ///< Shortcut for frame.origin.x + frame.size.width
@property (nonatomic) CGFloat bottom; ///< Shortcut for frame.origin.y + frame.size.height
@property (nonatomic) CGFloat width; ///< Shortcut for frame.size.width.
@property (nonatomic) CGFloat height; ///< Shortcut for frame.size.height.
@property (nonatomic) CGPoint center; ///< Shortcut for center.
@property (nonatomic) CGFloat centerX; ///< Shortcut for center.x
@property (nonatomic) CGFloat centerY; ///< Shortcut for center.y
@property (nonatomic) CGPoint origin; ///< Shortcut for frame.origin.
@property (nonatomic, getter=frameSize, setter=setFrameSize:) CGSize size; ///< Shortcut for frame.size.
@property (nonatomic) CGFloat transformRotation; ///< key path "tranform.rotation"
@property (nonatomic) CGFloat transformRotationX; ///< key path "tranform.rotation.x"
@property (nonatomic) CGFloat transformRotationY; ///< key path "tranform.rotation.y"
@property (nonatomic) CGFloat transformRotationZ; ///< key path "tranform.rotation.z"
@property (nonatomic) CGFloat transformScale; ///< key path "tranform.scale"
@property (nonatomic) CGFloat transformScaleX; ///< key path "tranform.scale.x"
@property (nonatomic) CGFloat transformScaleY; ///< key path "tranform.scale.y"
@property (nonatomic) CGFloat transformScaleZ; ///< key path "tranform.scale.z"
@property (nonatomic) CGFloat transformTranslationX; ///< key path "tranform.translation.x"
@property (nonatomic) CGFloat transformTranslationY; ///< key path "tranform.translation.y"
@property (nonatomic) CGFloat transformTranslationZ; ///< key path "tranform.translation.z"
/**
Shortcut for transform.m34, -1/1000 is a good value.
It should be set before other transform shortcut.
*/
@property (nonatomic) CGFloat transformDepth;
/**
Wrapper for `contentsGravity` property.
*/
@property (nonatomic) UIViewContentMode contentMode;
/**
Add a fade animation to layer's contents when the contents is changed.
@param duration Animation duration
@param curve Animation curve.
*/
- (void)addFadeAnimationWithDuration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve;
/**
Cancel fade animation which is added with "-addFadeAnimationWithDuration:curve:".
*/
- (void)removePreviousFadeAnimation;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Quartz/CALayer+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 735
|
```objective-c
//
// YYCGUtilities.h
// YYKit <path_to_url
//
// Created by ibireme on 15/2/28.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#if __has_include(<YYKit/YYKit.h>)
#import <YYKit/YYKitMacro.h>
#else
#import "YYKitMacro.h"
#endif
YY_EXTERN_C_BEGIN
NS_ASSUME_NONNULL_BEGIN
/// Create an `ARGB` Bitmap context. Returns NULL if an error occurs.
///
/// @discussion The function is same as UIGraphicsBeginImageContextWithOptions(),
/// but it doesn't push the context to UIGraphic, so you can retain the context for reuse.
CGContextRef _Nullable YYCGContextCreateARGBBitmapContext(CGSize size, BOOL opaque, CGFloat scale);
/// Create a `DeviceGray` Bitmap context. Returns NULL if an error occurs.
CGContextRef _Nullable YYCGContextCreateGrayBitmapContext(CGSize size, CGFloat scale);
/// Get main screen's scale.
CGFloat YYScreenScale();
/// Get main screen's size. Height is always larger than width.
CGSize YYScreenSize();
/// Convert degrees to radians.
static inline CGFloat DegreesToRadians(CGFloat degrees) {
return degrees * M_PI / 180;
}
/// Convert radians to degrees.
static inline CGFloat RadiansToDegrees(CGFloat radians) {
return radians * 180 / M_PI;
}
/// Get the transform rotation.
/// @return the rotation in radians [-PI,PI] ([-180,180])
static inline CGFloat CGAffineTransformGetRotation(CGAffineTransform transform) {
return atan2(transform.b, transform.a);
}
/// Get the transform's scale.x
static inline CGFloat CGAffineTransformGetScaleX(CGAffineTransform transform) {
return sqrt(transform.a * transform.a + transform.c * transform.c);
}
/// Get the transform's scale.y
static inline CGFloat CGAffineTransformGetScaleY(CGAffineTransform transform) {
return sqrt(transform.b * transform.b + transform.d * transform.d);
}
/// Get the transform's translate.x
static inline CGFloat CGAffineTransformGetTranslateX(CGAffineTransform transform) {
return transform.tx;
}
/// Get the transform's translate.y
static inline CGFloat CGAffineTransformGetTranslateY(CGAffineTransform transform) {
return transform.ty;
}
/**
If you have 3 pair of points transformed by a same CGAffineTransform:
p1 (transform->) q1
p2 (transform->) q2
p3 (transform->) q3
This method returns the original transform matrix from these 3 pair of points.
@see path_to_url
*/
CGAffineTransform YYCGAffineTransformGetFromPoints(CGPoint before[3], CGPoint after[3]);
/// Get the transform which can converts a point from the coordinate system of a given view to another.
CGAffineTransform YYCGAffineTransformGetFromViews(UIView *from, UIView *to);
/// Create a skew transform.
static inline CGAffineTransform CGAffineTransformMakeSkew(CGFloat x, CGFloat y){
CGAffineTransform transform = CGAffineTransformIdentity;
transform.c = -x;
transform.b = y;
return transform;
}
/// Negates/inverts a UIEdgeInsets.
static inline UIEdgeInsets UIEdgeInsetsInvert(UIEdgeInsets insets) {
return UIEdgeInsetsMake(-insets.top, -insets.left, -insets.bottom, -insets.right);
}
/// Convert CALayer's gravity string to UIViewContentMode.
UIViewContentMode YYCAGravityToUIViewContentMode(NSString *gravity);
/// Convert UIViewContentMode to CALayer's gravity string.
NSString *YYUIViewContentModeToCAGravity(UIViewContentMode contentMode);
/**
Returns a rectangle to fit the @param rect with specified content mode.
@param rect The constrant rect
@param size The content size
@param mode The content mode
@return A rectangle for the given content mode.
@discussion UIViewContentModeRedraw is same as UIViewContentModeScaleToFill.
*/
CGRect YYCGRectFitWithContentMode(CGRect rect, CGSize size, UIViewContentMode mode);
/// Returns the center for the rectangle.
static inline CGPoint CGRectGetCenter(CGRect rect) {
return CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
}
/// Returns the area of the rectangle.
static inline CGFloat CGRectGetArea(CGRect rect) {
if (CGRectIsNull(rect)) return 0;
rect = CGRectStandardize(rect);
return rect.size.width * rect.size.height;
}
/// Returns the distance between two points.
static inline CGFloat CGPointGetDistanceToPoint(CGPoint p1, CGPoint p2) {
return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}
/// Returns the minmium distance between a point to a rectangle.
static inline CGFloat CGPointGetDistanceToRect(CGPoint p, CGRect r) {
r = CGRectStandardize(r);
if (CGRectContainsPoint(r, p)) return 0;
CGFloat distV, distH;
if (CGRectGetMinY(r) <= p.y && p.y <= CGRectGetMaxY(r)) {
distV = 0;
} else {
distV = p.y < CGRectGetMinY(r) ? CGRectGetMinY(r) - p.y : p.y - CGRectGetMaxY(r);
}
if (CGRectGetMinX(r) <= p.x && p.x <= CGRectGetMaxX(r)) {
distH = 0;
} else {
distH = p.x < CGRectGetMinX(r) ? CGRectGetMinX(r) - p.x : p.x - CGRectGetMaxX(r);
}
return MAX(distV, distH);
}
/// Convert point to pixel.
static inline CGFloat CGFloatToPixel(CGFloat value) {
return value * YYScreenScale();
}
/// Convert pixel to point.
static inline CGFloat CGFloatFromPixel(CGFloat value) {
return value / YYScreenScale();
}
/// floor point value for pixel-aligned
static inline CGFloat CGFloatPixelFloor(CGFloat value) {
CGFloat scale = YYScreenScale();
return floor(value * scale) / scale;
}
/// round point value for pixel-aligned
static inline CGFloat CGFloatPixelRound(CGFloat value) {
CGFloat scale = YYScreenScale();
return round(value * scale) / scale;
}
/// ceil point value for pixel-aligned
static inline CGFloat CGFloatPixelCeil(CGFloat value) {
CGFloat scale = YYScreenScale();
return ceil(value * scale) / scale;
}
/// round point value to .5 pixel for path stroke (odd pixel line width pixel-aligned)
static inline CGFloat CGFloatPixelHalf(CGFloat value) {
CGFloat scale = YYScreenScale();
return (floor(value * scale) + 0.5) / scale;
}
/// floor point value for pixel-aligned
static inline CGPoint CGPointPixelFloor(CGPoint point) {
CGFloat scale = YYScreenScale();
return CGPointMake(floor(point.x * scale) / scale,
floor(point.y * scale) / scale);
}
/// round point value for pixel-aligned
static inline CGPoint CGPointPixelRound(CGPoint point) {
CGFloat scale = YYScreenScale();
return CGPointMake(round(point.x * scale) / scale,
round(point.y * scale) / scale);
}
/// ceil point value for pixel-aligned
static inline CGPoint CGPointPixelCeil(CGPoint point) {
CGFloat scale = YYScreenScale();
return CGPointMake(ceil(point.x * scale) / scale,
ceil(point.y * scale) / scale);
}
/// round point value to .5 pixel for path stroke (odd pixel line width pixel-aligned)
static inline CGPoint CGPointPixelHalf(CGPoint point) {
CGFloat scale = YYScreenScale();
return CGPointMake((floor(point.x * scale) + 0.5) / scale,
(floor(point.y * scale) + 0.5) / scale);
}
/// floor point value for pixel-aligned
static inline CGSize CGSizePixelFloor(CGSize size) {
CGFloat scale = YYScreenScale();
return CGSizeMake(floor(size.width * scale) / scale,
floor(size.height * scale) / scale);
}
/// round point value for pixel-aligned
static inline CGSize CGSizePixelRound(CGSize size) {
CGFloat scale = YYScreenScale();
return CGSizeMake(round(size.width * scale) / scale,
round(size.height * scale) / scale);
}
/// ceil point value for pixel-aligned
static inline CGSize CGSizePixelCeil(CGSize size) {
CGFloat scale = YYScreenScale();
return CGSizeMake(ceil(size.width * scale) / scale,
ceil(size.height * scale) / scale);
}
/// round point value to .5 pixel for path stroke (odd pixel line width pixel-aligned)
static inline CGSize CGSizePixelHalf(CGSize size) {
CGFloat scale = YYScreenScale();
return CGSizeMake((floor(size.width * scale) + 0.5) / scale,
(floor(size.height * scale) + 0.5) / scale);
}
/// floor point value for pixel-aligned
static inline CGRect CGRectPixelFloor(CGRect rect) {
CGPoint origin = CGPointPixelCeil(rect.origin);
CGPoint corner = CGPointPixelFloor(CGPointMake(rect.origin.x + rect.size.width,
rect.origin.y + rect.size.height));
CGRect ret = CGRectMake(origin.x, origin.y, corner.x - origin.x, corner.y - origin.y);
if (ret.size.width < 0) ret.size.width = 0;
if (ret.size.height < 0) ret.size.height = 0;
return ret;
}
/// round point value for pixel-aligned
static inline CGRect CGRectPixelRound(CGRect rect) {
CGPoint origin = CGPointPixelRound(rect.origin);
CGPoint corner = CGPointPixelRound(CGPointMake(rect.origin.x + rect.size.width,
rect.origin.y + rect.size.height));
return CGRectMake(origin.x, origin.y, corner.x - origin.x, corner.y - origin.y);
}
/// ceil point value for pixel-aligned
static inline CGRect CGRectPixelCeil(CGRect rect) {
CGPoint origin = CGPointPixelFloor(rect.origin);
CGPoint corner = CGPointPixelCeil(CGPointMake(rect.origin.x + rect.size.width,
rect.origin.y + rect.size.height));
return CGRectMake(origin.x, origin.y, corner.x - origin.x, corner.y - origin.y);
}
/// round point value to .5 pixel for path stroke (odd pixel line width pixel-aligned)
static inline CGRect CGRectPixelHalf(CGRect rect) {
CGPoint origin = CGPointPixelHalf(rect.origin);
CGPoint corner = CGPointPixelHalf(CGPointMake(rect.origin.x + rect.size.width,
rect.origin.y + rect.size.height));
return CGRectMake(origin.x, origin.y, corner.x - origin.x, corner.y - origin.y);
}
/// floor UIEdgeInset for pixel-aligned
static inline UIEdgeInsets UIEdgeInsetPixelFloor(UIEdgeInsets insets) {
insets.top = CGFloatPixelFloor(insets.top);
insets.left = CGFloatPixelFloor(insets.left);
insets.bottom = CGFloatPixelFloor(insets.bottom);
insets.right = CGFloatPixelFloor(insets.right);
return insets;
}
/// ceil UIEdgeInset for pixel-aligned
static inline UIEdgeInsets UIEdgeInsetPixelCeil(UIEdgeInsets insets) {
insets.top = CGFloatPixelCeil(insets.top);
insets.left = CGFloatPixelCeil(insets.left);
insets.bottom = CGFloatPixelCeil(insets.bottom);
insets.right = CGFloatPixelCeil(insets.right);
return insets;
}
// main screen's scale
#ifndef kScreenScale
#define kScreenScale YYScreenScale()
#endif
// main screen's size (portrait)
#ifndef kScreenSize
#define kScreenSize YYScreenSize()
#endif
// main screen's width (portrait)
#ifndef kScreenWidth
#define kScreenWidth YYScreenSize().width
#endif
// main screen's height (portrait)
#ifndef kScreenHeight
#define kScreenHeight YYScreenSize().height
#endif
NS_ASSUME_NONNULL_END
YY_EXTERN_C_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Quartz/YYCGUtilities.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 2,502
|
```objective-c
//
// YYCGUtilities.m
// YYKit <path_to_url
//
// Created by ibireme on 15/2/28.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "YYCGUtilities.h"
#import <Accelerate/Accelerate.h>
#import "UIView+YYAdd.h"
CGContextRef YYCGContextCreateARGBBitmapContext(CGSize size, BOOL opaque, CGFloat scale) {
size_t width = ceil(size.width * scale);
size_t height = ceil(size.height * scale);
if (width < 1 || height < 1) return NULL;
//pre-multiplied ARGB, 8-bits per component
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGImageAlphaInfo alphaInfo = (opaque ? kCGImageAlphaNoneSkipFirst : kCGImageAlphaPremultipliedFirst);
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, space, kCGBitmapByteOrderDefault | alphaInfo);
CGColorSpaceRelease(space);
if (context) {
CGContextTranslateCTM(context, 0, height);
CGContextScaleCTM(context, scale, -scale);
}
return context;
}
CGContextRef YYCGContextCreateGrayBitmapContext(CGSize size, CGFloat scale) {
size_t width = ceil(size.width * scale);
size_t height = ceil(size.height * scale);
if (width < 1 || height < 1) return NULL;
//DeviceGray, 8-bits per component
CGColorSpaceRef space = CGColorSpaceCreateDeviceGray();
CGImageAlphaInfo alphaInfo = kCGImageAlphaNone;
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, space, kCGBitmapByteOrderDefault | alphaInfo);
CGColorSpaceRelease(space);
if (context) {
CGContextTranslateCTM(context, 0, height);
CGContextScaleCTM(context, scale, -scale);
}
return context;
}
CGFloat YYScreenScale() {
static CGFloat scale;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
scale = [UIScreen mainScreen].scale;
});
return scale;
}
CGSize YYScreenSize() {
static CGSize size;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
size = [UIScreen mainScreen].bounds.size;
if (size.height < size.width) {
CGFloat tmp = size.height;
size.height = size.width;
size.width = tmp;
}
});
return size;
}
// return 0 when succeed
static int matrix_invert(__CLPK_integer N, double *matrix) {
__CLPK_integer error = 0;
__CLPK_integer pivot_tmp[6 * 6];
__CLPK_integer *pivot = pivot_tmp;
double workspace_tmp[6 * 6];
double *workspace = workspace_tmp;
bool need_free = false;
if (N > 6) {
need_free = true;
pivot = malloc(N * N * sizeof(__CLPK_integer));
if (!pivot) return -1;
workspace = malloc(N * sizeof(double));
if (!workspace) {
free(pivot);
return -1;
}
}
dgetrf_(&N, &N, matrix, &N, pivot, &error);
if (error == 0) {
dgetri_(&N, matrix, &N, pivot, workspace, &N, &error);
}
if (need_free) {
free(pivot);
free(workspace);
}
return error;
}
CGAffineTransform YYCGAffineTransformGetFromPoints(CGPoint before[3], CGPoint after[3]) {
if (before == NULL || after == NULL) return CGAffineTransformIdentity;
CGPoint p1, p2, p3, q1, q2, q3;
p1 = before[0]; p2 = before[1]; p3 = before[2];
q1 = after[0]; q2 = after[1]; q3 = after[2];
double A[36];
A[ 0] = p1.x; A[ 1] = p1.y; A[ 2] = 0; A[ 3] = 0; A[ 4] = 1; A[ 5] = 0;
A[ 6] = 0; A[ 7] = 0; A[ 8] = p1.x; A[ 9] = p1.y; A[10] = 0; A[11] = 1;
A[12] = p2.x; A[13] = p2.y; A[14] = 0; A[15] = 0; A[16] = 1; A[17] = 0;
A[18] = 0; A[19] = 0; A[20] = p2.x; A[21] = p2.y; A[22] = 0; A[23] = 1;
A[24] = p3.x; A[25] = p3.y; A[26] = 0; A[27] = 0; A[28] = 1; A[29] = 0;
A[30] = 0; A[31] = 0; A[32] = p3.x; A[33] = p3.y; A[34] = 0; A[35] = 1;
int error = matrix_invert(6, A);
if (error) return CGAffineTransformIdentity;
double B[6];
B[0] = q1.x; B[1] = q1.y; B[2] = q2.x; B[3] = q2.y; B[4] = q3.x; B[5] = q3.y;
double M[6];
M[0] = A[ 0] * B[0] + A[ 1] * B[1] + A[ 2] * B[2] + A[ 3] * B[3] + A[ 4] * B[4] + A[ 5] * B[5];
M[1] = A[ 6] * B[0] + A[ 7] * B[1] + A[ 8] * B[2] + A[ 9] * B[3] + A[10] * B[4] + A[11] * B[5];
M[2] = A[12] * B[0] + A[13] * B[1] + A[14] * B[2] + A[15] * B[3] + A[16] * B[4] + A[17] * B[5];
M[3] = A[18] * B[0] + A[19] * B[1] + A[20] * B[2] + A[21] * B[3] + A[22] * B[4] + A[23] * B[5];
M[4] = A[24] * B[0] + A[25] * B[1] + A[26] * B[2] + A[27] * B[3] + A[28] * B[4] + A[29] * B[5];
M[5] = A[30] * B[0] + A[31] * B[1] + A[32] * B[2] + A[33] * B[3] + A[34] * B[4] + A[35] * B[5];
CGAffineTransform transform = CGAffineTransformMake(M[0], M[2], M[1], M[3], M[4], M[5]);
return transform;
}
CGAffineTransform YYCGAffineTransformGetFromViews(UIView *from, UIView *to) {
if (!from || !to) return CGAffineTransformIdentity;
CGPoint before[3], after[3];
before[0] = CGPointMake(0, 0);
before[1] = CGPointMake(0, 1);
before[2] = CGPointMake(1, 0);
after[0] = [from convertPoint:before[0] toViewOrWindow:to];
after[1] = [from convertPoint:before[1] toViewOrWindow:to];
after[2] = [from convertPoint:before[2] toViewOrWindow:to];
return YYCGAffineTransformGetFromPoints(before, after);
}
UIViewContentMode YYCAGravityToUIViewContentMode(NSString *gravity) {
static NSDictionary *dic;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dic = @{ kCAGravityCenter:@(UIViewContentModeCenter),
kCAGravityTop:@(UIViewContentModeTop),
kCAGravityBottom:@(UIViewContentModeBottom),
kCAGravityLeft:@(UIViewContentModeLeft),
kCAGravityRight:@(UIViewContentModeRight),
kCAGravityTopLeft:@(UIViewContentModeTopLeft),
kCAGravityTopRight:@(UIViewContentModeTopRight),
kCAGravityBottomLeft:@(UIViewContentModeBottomLeft),
kCAGravityBottomRight:@(UIViewContentModeBottomRight),
kCAGravityResize:@(UIViewContentModeScaleToFill),
kCAGravityResizeAspect:@(UIViewContentModeScaleAspectFit),
kCAGravityResizeAspectFill:@(UIViewContentModeScaleAspectFill) };
});
if (!gravity) return UIViewContentModeScaleToFill;
return (UIViewContentMode)((NSNumber *)dic[gravity]).integerValue;
}
NSString *YYUIViewContentModeToCAGravity(UIViewContentMode contentMode) {
switch (contentMode) {
case UIViewContentModeScaleToFill: return kCAGravityResize;
case UIViewContentModeScaleAspectFit: return kCAGravityResizeAspect;
case UIViewContentModeScaleAspectFill: return kCAGravityResizeAspectFill;
case UIViewContentModeRedraw: return kCAGravityResize;
case UIViewContentModeCenter: return kCAGravityCenter;
case UIViewContentModeTop: return kCAGravityTop;
case UIViewContentModeBottom: return kCAGravityBottom;
case UIViewContentModeLeft: return kCAGravityLeft;
case UIViewContentModeRight: return kCAGravityRight;
case UIViewContentModeTopLeft: return kCAGravityTopLeft;
case UIViewContentModeTopRight: return kCAGravityTopRight;
case UIViewContentModeBottomLeft: return kCAGravityBottomLeft;
case UIViewContentModeBottomRight: return kCAGravityBottomRight;
default: return kCAGravityResize;
}
}
CGRect YYCGRectFitWithContentMode(CGRect rect, CGSize size, UIViewContentMode mode) {
rect = CGRectStandardize(rect);
size.width = size.width < 0 ? -size.width : size.width;
size.height = size.height < 0 ? -size.height : size.height;
CGPoint center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
switch (mode) {
case UIViewContentModeScaleAspectFit:
case UIViewContentModeScaleAspectFill: {
if (rect.size.width < 0.01 || rect.size.height < 0.01 ||
size.width < 0.01 || size.height < 0.01) {
rect.origin = center;
rect.size = CGSizeZero;
} else {
CGFloat scale;
if (mode == UIViewContentModeScaleAspectFit) {
if (size.width / size.height < rect.size.width / rect.size.height) {
scale = rect.size.height / size.height;
} else {
scale = rect.size.width / size.width;
}
} else {
if (size.width / size.height < rect.size.width / rect.size.height) {
scale = rect.size.width / size.width;
} else {
scale = rect.size.height / size.height;
}
}
size.width *= scale;
size.height *= scale;
rect.size = size;
rect.origin = CGPointMake(center.x - size.width * 0.5, center.y - size.height * 0.5);
}
} break;
case UIViewContentModeCenter: {
rect.size = size;
rect.origin = CGPointMake(center.x - size.width * 0.5, center.y - size.height * 0.5);
} break;
case UIViewContentModeTop: {
rect.origin.x = center.x - size.width * 0.5;
rect.size = size;
} break;
case UIViewContentModeBottom: {
rect.origin.x = center.x - size.width * 0.5;
rect.origin.y += rect.size.height - size.height;
rect.size = size;
} break;
case UIViewContentModeLeft: {
rect.origin.y = center.y - size.height * 0.5;
rect.size = size;
} break;
case UIViewContentModeRight: {
rect.origin.y = center.y - size.height * 0.5;
rect.origin.x += rect.size.width - size.width;
rect.size = size;
} break;
case UIViewContentModeTopLeft: {
rect.size = size;
} break;
case UIViewContentModeTopRight: {
rect.origin.x += rect.size.width - size.width;
rect.size = size;
} break;
case UIViewContentModeBottomLeft: {
rect.origin.y += rect.size.height - size.height;
rect.size = size;
} break;
case UIViewContentModeBottomRight: {
rect.origin.x += rect.size.width - size.width;
rect.origin.y += rect.size.height - size.height;
rect.size = size;
} break;
case UIViewContentModeScaleToFill:
case UIViewContentModeRedraw:
default: {
rect = rect;
}
}
return rect;
}
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Quartz/YYCGUtilities.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 3,123
|
```objective-c
//
// UIScrollView+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 13/4/5.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "UIScrollView+YYAdd.h"
#import "YYKitMacro.h"
YYSYNTH_DUMMY_CLASS(UIScrollView_YYAdd)
@implementation UIScrollView (YYAdd)
- (void)scrollToTop {
[self scrollToTopAnimated:YES];
}
- (void)scrollToBottom {
[self scrollToBottomAnimated:YES];
}
- (void)scrollToLeft {
[self scrollToLeftAnimated:YES];
}
- (void)scrollToRight {
[self scrollToRightAnimated:YES];
}
- (void)scrollToTopAnimated:(BOOL)animated {
CGPoint off = self.contentOffset;
off.y = 0 - self.contentInset.top;
[self setContentOffset:off animated:animated];
}
- (void)scrollToBottomAnimated:(BOOL)animated {
CGPoint off = self.contentOffset;
off.y = self.contentSize.height - self.bounds.size.height + self.contentInset.bottom;
[self setContentOffset:off animated:animated];
}
- (void)scrollToLeftAnimated:(BOOL)animated {
CGPoint off = self.contentOffset;
off.x = 0 - self.contentInset.left;
[self setContentOffset:off animated:animated];
}
- (void)scrollToRightAnimated:(BOOL)animated {
CGPoint off = self.contentOffset;
off.x = self.contentSize.width - self.bounds.size.width + self.contentInset.right;
[self setContentOffset:off animated:animated];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIScrollView+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 349
|
```objective-c
//
// UITableView+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 14/5/12.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "UITableView+YYAdd.h"
#import "YYKitMacro.h"
YYSYNTH_DUMMY_CLASS(UITableView_YYAdd)
@implementation UITableView (YYAdd)
- (void)updateWithBlock:(void (^)(UITableView *tableView))block {
[self beginUpdates];
block(self);
[self endUpdates];
}
- (void)scrollToRow:(NSUInteger)row inSection:(NSUInteger)section atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
[self scrollToRowAtIndexPath:indexPath atScrollPosition:scrollPosition animated:animated];
}
- (void)insertRowAtIndexPath:(NSIndexPath *)indexPath withRowAnimation:(UITableViewRowAnimation)animation {
[self insertRowsAtIndexPaths:@[indexPath] withRowAnimation:animation];
}
- (void)insertRow:(NSUInteger)row inSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation {
NSIndexPath *toInsert = [NSIndexPath indexPathForRow:row inSection:section];
[self insertRowAtIndexPath:toInsert withRowAnimation:animation];
}
- (void)reloadRowAtIndexPath:(NSIndexPath *)indexPath withRowAnimation:(UITableViewRowAnimation)animation {
[self reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:animation];
}
- (void)reloadRow:(NSUInteger)row inSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation {
NSIndexPath *toReload = [NSIndexPath indexPathForRow:row inSection:section];
[self reloadRowAtIndexPath:toReload withRowAnimation:animation];
}
- (void)deleteRowAtIndexPath:(NSIndexPath *)indexPath withRowAnimation:(UITableViewRowAnimation)animation {
[self deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:animation];
}
- (void)deleteRow:(NSUInteger)row inSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation {
NSIndexPath *toDelete = [NSIndexPath indexPathForRow:row inSection:section];
[self deleteRowAtIndexPath:toDelete withRowAnimation:animation];
}
- (void)insertSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation {
NSIndexSet *sections = [NSIndexSet indexSetWithIndex:section];
[self insertSections:sections withRowAnimation:animation];
}
- (void)deleteSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation {
NSIndexSet *sections = [NSIndexSet indexSetWithIndex:section];
[self deleteSections:sections withRowAnimation:animation];
}
- (void)reloadSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation {
NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:section];
[self reloadSections:indexSet withRowAnimation:animation];
}
- (void)clearSelectedRowsAnimated:(BOOL)animated {
NSArray *indexs = [self indexPathsForSelectedRows];
[indexs enumerateObjectsUsingBlock:^(NSIndexPath* path, NSUInteger idx, BOOL *stop) {
[self deselectRowAtIndexPath:path animated:animated];
}];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UITableView+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 668
|
```objective-c
//
// UIFont+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 14/5/11.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "UIFont+YYAdd.h"
#import "YYKitMacro.h"
YYSYNTH_DUMMY_CLASS(UIFont_YYAdd)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wprotocol"
// Apple has implemented UIFont<NSCoding>, but did not make it public.
@implementation UIFont (YYAdd)
- (BOOL)isBold {
if (![self respondsToSelector:@selector(fontDescriptor)]) return NO;
return (self.fontDescriptor.symbolicTraits & UIFontDescriptorTraitBold) > 0;
}
- (BOOL)isItalic {
if (![self respondsToSelector:@selector(fontDescriptor)]) return NO;
return (self.fontDescriptor.symbolicTraits & UIFontDescriptorTraitItalic) > 0;
}
- (BOOL)isMonoSpace {
if (![self respondsToSelector:@selector(fontDescriptor)]) return NO;
return (self.fontDescriptor.symbolicTraits & UIFontDescriptorTraitMonoSpace) > 0;
}
- (BOOL)isColorGlyphs {
if (![self respondsToSelector:@selector(fontDescriptor)]) return NO;
return (CTFontGetSymbolicTraits((__bridge CTFontRef)self) & kCTFontTraitColorGlyphs) != 0;
}
- (CGFloat)fontWeight {
NSDictionary *traits = [self.fontDescriptor objectForKey:UIFontDescriptorTraitsAttribute];
return [traits[UIFontWeightTrait] floatValue];
}
- (UIFont *)fontWithBold {
if (![self respondsToSelector:@selector(fontDescriptor)]) return self;
return [UIFont fontWithDescriptor:[self.fontDescriptor fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold] size:self.pointSize];
}
- (UIFont *)fontWithItalic {
if (![self respondsToSelector:@selector(fontDescriptor)]) return self;
return [UIFont fontWithDescriptor:[self.fontDescriptor fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitItalic] size:self.pointSize];
}
- (UIFont *)fontWithBoldItalic {
if (![self respondsToSelector:@selector(fontDescriptor)]) return self;
return [UIFont fontWithDescriptor:[self.fontDescriptor fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold | UIFontDescriptorTraitItalic] size:self.pointSize];
}
- (UIFont *)fontWithNormal {
if (![self respondsToSelector:@selector(fontDescriptor)]) return self;
return [UIFont fontWithDescriptor:[self.fontDescriptor fontDescriptorWithSymbolicTraits:0] size:self.pointSize];
}
+ (UIFont *)fontWithCTFont:(CTFontRef)CTFont {
if (!CTFont) return nil;
CFStringRef name = CTFontCopyPostScriptName(CTFont);
if (!name) return nil;
CGFloat size = CTFontGetSize(CTFont);
UIFont *font = [self fontWithName:(__bridge NSString *)(name) size:size];
CFRelease(name);
return font;
}
+ (UIFont *)fontWithCGFont:(CGFontRef)CGFont size:(CGFloat)size {
if (!CGFont) return nil;
CFStringRef name = CGFontCopyPostScriptName(CGFont);
if (!name) return nil;
UIFont *font = [self fontWithName:(__bridge NSString *)(name) size:size];
CFRelease(name);
return font;
}
- (CTFontRef)CTFontRef CF_RETURNS_RETAINED {
CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)self.fontName, self.pointSize, NULL);
return font;
}
- (CGFontRef)CGFontRef CF_RETURNS_RETAINED {
CGFontRef font = CGFontCreateWithFontName((__bridge CFStringRef)self.fontName);
return font;
}
+ (BOOL)loadFontFromPath:(NSString *)path {
NSURL *url = [NSURL fileURLWithPath:path];
CFErrorRef error;
BOOL suc = CTFontManagerRegisterFontsForURL((__bridge CFTypeRef)url, kCTFontManagerScopeNone, &error);
if (!suc) {
NSLog(@"Failed to load font: %@", error);
}
return suc;
}
+ (void)unloadFontFromPath:(NSString *)path {
NSURL *url = [NSURL fileURLWithPath:path];
CTFontManagerUnregisterFontsForURL((__bridge CFTypeRef)url, kCTFontManagerScopeNone, NULL);
}
+ (UIFont *)loadFontFromData:(NSData *)data {
CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
if (!provider) return nil;
CGFontRef fontRef = CGFontCreateWithDataProvider(provider);
CGDataProviderRelease(provider);
if (!fontRef) return nil;
CFErrorRef errorRef;
BOOL suc = CTFontManagerRegisterGraphicsFont(fontRef, &errorRef);
if (!suc) {
CFRelease(fontRef);
NSLog(@"%@", errorRef);
return nil;
} else {
CFStringRef fontName = CGFontCopyPostScriptName(fontRef);
UIFont *font = [UIFont fontWithName:(__bridge NSString *)(fontName) size:[UIFont systemFontSize]];
if (fontName) CFRelease(fontName);
CGFontRelease(fontRef);
return font;
}
}
+ (BOOL)unloadFontFromData:(UIFont *)font {
CGFontRef fontRef = CGFontCreateWithFontName((__bridge CFStringRef)font.fontName);
if (!fontRef) return NO;
CFErrorRef errorRef;
BOOL suc = CTFontManagerUnregisterGraphicsFont(fontRef, &errorRef);
CFRelease(fontRef);
if (!suc) NSLog(@"%@", errorRef);
return suc;
}
+ (NSData *)dataFromFont:(UIFont *)font {
CGFontRef cgFont = font.CGFontRef;
NSData *data = [self dataFromCGFont:cgFont];
CGFontRelease(cgFont);
return data;
}
typedef struct FontHeader {
int32_t fVersion;
uint16_t fNumTables;
uint16_t fSearchRange;
uint16_t fEntrySelector;
uint16_t fRangeShift;
} FontHeader;
typedef struct TableEntry {
uint32_t fTag;
uint32_t fCheckSum;
uint32_t fOffset;
uint32_t fLength;
} TableEntry;
static uint32_t CalcTableCheckSum(const uint32_t *table, uint32_t numberOfBytesInTable) {
uint32_t sum = 0;
uint32_t nLongs = (numberOfBytesInTable + 3) / 4;
while (nLongs-- > 0) {
sum += CFSwapInt32HostToBig(*table++);
}
return sum;
}
//Reference:
//path_to_url
+ (NSData *)dataFromCGFont:(CGFontRef)cgFont {
if (!cgFont) return nil;
CFRetain(cgFont);
CFArrayRef tags = CGFontCopyTableTags(cgFont);
if (!tags) return nil;
CFIndex tableCount = CFArrayGetCount(tags);
size_t *tableSizes = malloc(sizeof(size_t) * tableCount);
memset(tableSizes, 0, sizeof(size_t) * tableCount);
BOOL containsCFFTable = NO;
size_t totalSize = sizeof(FontHeader) + sizeof(TableEntry) * tableCount;
for (CFIndex index = 0; index < tableCount; index++) {
size_t tableSize = 0;
uint32_t aTag = (uint32_t)CFArrayGetValueAtIndex(tags, index);
if (aTag == kCTFontTableCFF && !containsCFFTable) {
containsCFFTable = YES;
}
CFDataRef tableDataRef = CGFontCopyTableForTag(cgFont, aTag);
if (tableDataRef) {
tableSize = CFDataGetLength(tableDataRef);
CFRelease(tableDataRef);
}
totalSize += (tableSize + 3) & ~3;
tableSizes[index] = tableSize;
}
unsigned char *stream = malloc(totalSize);
memset(stream, 0, totalSize);
char *dataStart = (char *)stream;
char *dataPtr = dataStart;
// compute font header entries
uint16_t entrySelector = 0;
uint16_t searchRange = 1;
while (searchRange < tableCount >> 1) {
entrySelector++;
searchRange <<= 1;
}
searchRange <<= 4;
uint16_t rangeShift = (tableCount << 4) - searchRange;
// write font header (also called sfnt header, offset subtable)
FontHeader *offsetTable = (FontHeader *)dataPtr;
//OpenType Font contains CFF Table use 'OTTO' as version, and with .otf extension
//otherwise 0001 0000
offsetTable->fVersion = containsCFFTable ? 'OTTO' : CFSwapInt16HostToBig(1);
offsetTable->fNumTables = CFSwapInt16HostToBig((uint16_t)tableCount);
offsetTable->fSearchRange = CFSwapInt16HostToBig((uint16_t)searchRange);
offsetTable->fEntrySelector = CFSwapInt16HostToBig((uint16_t)entrySelector);
offsetTable->fRangeShift = CFSwapInt16HostToBig((uint16_t)rangeShift);
dataPtr += sizeof(FontHeader);
// write tables
TableEntry *entry = (TableEntry *)dataPtr;
dataPtr += sizeof(TableEntry) * tableCount;
for (int index = 0; index < tableCount; ++index) {
uint32_t aTag = (uint32_t)CFArrayGetValueAtIndex(tags, index);
CFDataRef tableDataRef = CGFontCopyTableForTag(cgFont, aTag);
size_t tableSize = CFDataGetLength(tableDataRef);
memcpy(dataPtr, CFDataGetBytePtr(tableDataRef), tableSize);
entry->fTag = CFSwapInt32HostToBig((uint32_t)aTag);
entry->fCheckSum = CFSwapInt32HostToBig(CalcTableCheckSum((uint32_t *)dataPtr, (uint32_t)tableSize));
uint32_t offset = (uint32_t)dataPtr - (uint32_t)dataStart;
entry->fOffset = CFSwapInt32HostToBig((uint32_t)offset);
entry->fLength = CFSwapInt32HostToBig((uint32_t)tableSize);
dataPtr += (tableSize + 3) & ~3;
++entry;
CFRelease(tableDataRef);
}
CFRelease(cgFont);
CFRelease(tags);
free(tableSizes);
NSData *fontData = [NSData dataWithBytesNoCopy:stream length:totalSize freeWhenDone:YES];
return fontData;
}
@end
#pragma clang diagnostic pop
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIFont+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 2,370
|
```objective-c
//
// UIView+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 13/4/3.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "UIView+YYAdd.h"
#import <QuartzCore/QuartzCore.h>
#import "YYKitMacro.h"
YYSYNTH_DUMMY_CLASS(UIView_YYAdd)
@implementation UIView (YYAdd)
- (UIImage *)snapshotImage {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *snap = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return snap;
}
- (UIImage *)snapshotImageAfterScreenUpdates:(BOOL)afterUpdates {
if (![self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
return [self snapshotImage];
}
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0);
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:afterUpdates];
UIImage *snap = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return snap;
}
- (NSData *)snapshotPDF {
CGRect bounds = self.bounds;
NSMutableData *data = [NSMutableData data];
CGDataConsumerRef consumer = CGDataConsumerCreateWithCFData((__bridge CFMutableDataRef)data);
CGContextRef context = CGPDFContextCreate(consumer, &bounds, NULL);
CGDataConsumerRelease(consumer);
if (!context) return nil;
CGPDFContextBeginPage(context, NULL);
CGContextTranslateCTM(context, 0, bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
[self.layer renderInContext:context];
CGPDFContextEndPage(context);
CGPDFContextClose(context);
CGContextRelease(context);
return data;
}
- (void)setLayerShadow:(UIColor*)color offset:(CGSize)offset radius:(CGFloat)radius {
self.layer.shadowColor = color.CGColor;
self.layer.shadowOffset = offset;
self.layer.shadowRadius = radius;
self.layer.shadowOpacity = 1;
self.layer.shouldRasterize = YES;
self.layer.rasterizationScale = [UIScreen mainScreen].scale;
}
- (void)removeAllSubviews {
//[self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
while (self.subviews.count) {
[self.subviews.lastObject removeFromSuperview];
}
}
- (UIViewController *)viewController {
for (UIView *view = self; view; view = view.superview) {
UIResponder *nextResponder = [view nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]]) {
return (UIViewController *)nextResponder;
}
}
return nil;
}
- (CGFloat)visibleAlpha {
if ([self isKindOfClass:[UIWindow class]]) {
if (self.hidden) return 0;
return self.alpha;
}
if (!self.window) return 0;
CGFloat alpha = 1;
UIView *v = self;
while (v) {
if (v.hidden) {
alpha = 0;
break;
}
alpha *= v.alpha;
v = v.superview;
}
return alpha;
}
- (CGPoint)convertPoint:(CGPoint)point toViewOrWindow:(UIView *)view {
if (!view) {
if ([self isKindOfClass:[UIWindow class]]) {
return [((UIWindow *)self) convertPoint:point toWindow:nil];
} else {
return [self convertPoint:point toView:nil];
}
}
UIWindow *from = [self isKindOfClass:[UIWindow class]] ? (id)self : self.window;
UIWindow *to = [view isKindOfClass:[UIWindow class]] ? (id)view : view.window;
if ((!from || !to) || (from == to)) return [self convertPoint:point toView:view];
point = [self convertPoint:point toView:from];
point = [to convertPoint:point fromWindow:from];
point = [view convertPoint:point fromView:to];
return point;
}
- (CGPoint)convertPoint:(CGPoint)point fromViewOrWindow:(UIView *)view {
if (!view) {
if ([self isKindOfClass:[UIWindow class]]) {
return [((UIWindow *)self) convertPoint:point fromWindow:nil];
} else {
return [self convertPoint:point fromView:nil];
}
}
UIWindow *from = [view isKindOfClass:[UIWindow class]] ? (id)view : view.window;
UIWindow *to = [self isKindOfClass:[UIWindow class]] ? (id)self : self.window;
if ((!from || !to) || (from == to)) return [self convertPoint:point fromView:view];
point = [from convertPoint:point fromView:view];
point = [to convertPoint:point fromWindow:from];
point = [self convertPoint:point fromView:to];
return point;
}
- (CGRect)convertRect:(CGRect)rect toViewOrWindow:(UIView *)view {
if (!view) {
if ([self isKindOfClass:[UIWindow class]]) {
return [((UIWindow *)self) convertRect:rect toWindow:nil];
} else {
return [self convertRect:rect toView:nil];
}
}
UIWindow *from = [self isKindOfClass:[UIWindow class]] ? (id)self : self.window;
UIWindow *to = [view isKindOfClass:[UIWindow class]] ? (id)view : view.window;
if (!from || !to) return [self convertRect:rect toView:view];
if (from == to) return [self convertRect:rect toView:view];
rect = [self convertRect:rect toView:from];
rect = [to convertRect:rect fromWindow:from];
rect = [view convertRect:rect fromView:to];
return rect;
}
- (CGRect)convertRect:(CGRect)rect fromViewOrWindow:(UIView *)view {
if (!view) {
if ([self isKindOfClass:[UIWindow class]]) {
return [((UIWindow *)self) convertRect:rect fromWindow:nil];
} else {
return [self convertRect:rect fromView:nil];
}
}
UIWindow *from = [view isKindOfClass:[UIWindow class]] ? (id)view : view.window;
UIWindow *to = [self isKindOfClass:[UIWindow class]] ? (id)self : self.window;
if ((!from || !to) || (from == to)) return [self convertRect:rect fromView:view];
rect = [from convertRect:rect fromView:view];
rect = [to convertRect:rect fromWindow:from];
rect = [self convertRect:rect fromView:to];
return rect;
}
- (CGFloat)left {
return self.frame.origin.x;
}
- (void)setLeft:(CGFloat)x {
CGRect frame = self.frame;
frame.origin.x = x;
self.frame = frame;
}
- (CGFloat)top {
return self.frame.origin.y;
}
- (void)setTop:(CGFloat)y {
CGRect frame = self.frame;
frame.origin.y = y;
self.frame = frame;
}
- (CGFloat)right {
return self.frame.origin.x + self.frame.size.width;
}
- (void)setRight:(CGFloat)right {
CGRect frame = self.frame;
frame.origin.x = right - frame.size.width;
self.frame = frame;
}
- (CGFloat)bottom {
return self.frame.origin.y + self.frame.size.height;
}
- (void)setBottom:(CGFloat)bottom {
CGRect frame = self.frame;
frame.origin.y = bottom - frame.size.height;
self.frame = frame;
}
- (CGFloat)width {
return self.frame.size.width;
}
- (void)setWidth:(CGFloat)width {
CGRect frame = self.frame;
frame.size.width = width;
self.frame = frame;
}
- (CGFloat)height {
return self.frame.size.height;
}
- (void)setHeight:(CGFloat)height {
CGRect frame = self.frame;
frame.size.height = height;
self.frame = frame;
}
- (CGFloat)centerX {
return self.center.x;
}
- (void)setCenterX:(CGFloat)centerX {
self.center = CGPointMake(centerX, self.center.y);
}
- (CGFloat)centerY {
return self.center.y;
}
- (void)setCenterY:(CGFloat)centerY {
self.center = CGPointMake(self.center.x, centerY);
}
- (CGPoint)origin {
return self.frame.origin;
}
- (void)setOrigin:(CGPoint)origin {
CGRect frame = self.frame;
frame.origin = origin;
self.frame = frame;
}
- (CGSize)size {
return self.frame.size;
}
- (void)setSize:(CGSize)size {
CGRect frame = self.frame;
frame.size = size;
self.frame = frame;
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIView+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,928
|
```objective-c
//
// UIScrollView+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 13/4/5.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provides extensions for `UIScrollView`.
*/
@interface UIScrollView (YYAdd)
/**
Scroll content to top with animation.
*/
- (void)scrollToTop;
/**
Scroll content to bottom with animation.
*/
- (void)scrollToBottom;
/**
Scroll content to left with animation.
*/
- (void)scrollToLeft;
/**
Scroll content to right with animation.
*/
- (void)scrollToRight;
/**
Scroll content to top.
@param animated Use animation.
*/
- (void)scrollToTopAnimated:(BOOL)animated;
/**
Scroll content to bottom.
@param animated Use animation.
*/
- (void)scrollToBottomAnimated:(BOOL)animated;
/**
Scroll content to left.
@param animated Use animation.
*/
- (void)scrollToLeftAnimated:(BOOL)animated;
/**
Scroll content to right.
@param animated Use animation.
*/
- (void)scrollToRightAnimated:(BOOL)animated;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIScrollView+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 272
|
```objective-c
//
// UIGestureRecognizer+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 13/10/13.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "UIGestureRecognizer+YYAdd.h"
#import "YYKitMacro.h"
#import <objc/runtime.h>
static const int block_key;
@interface _YYUIGestureRecognizerBlockTarget : NSObject
@property (nonatomic, copy) void (^block)(id sender);
- (id)initWithBlock:(void (^)(id sender))block;
- (void)invoke:(id)sender;
@end
@implementation _YYUIGestureRecognizerBlockTarget
- (id)initWithBlock:(void (^)(id sender))block{
self = [super init];
if (self) {
_block = [block copy];
}
return self;
}
- (void)invoke:(id)sender {
if (_block) _block(sender);
}
@end
@implementation UIGestureRecognizer (YYAdd)
- (instancetype)initWithActionBlock:(void (^)(id sender))block {
self = [self init];
[self addActionBlock:block];
return self;
}
- (void)addActionBlock:(void (^)(id sender))block {
_YYUIGestureRecognizerBlockTarget *target = [[_YYUIGestureRecognizerBlockTarget alloc] initWithBlock:block];
[self addTarget:target action:@selector(invoke:)];
NSMutableArray *targets = [self _yy_allUIGestureRecognizerBlockTargets];
[targets addObject:target];
}
- (void)removeAllActionBlocks{
NSMutableArray *targets = [self _yy_allUIGestureRecognizerBlockTargets];
[targets enumerateObjectsUsingBlock:^(id target, NSUInteger idx, BOOL *stop) {
[self removeTarget:target action:@selector(invoke:)];
}];
[targets removeAllObjects];
}
- (NSMutableArray *)_yy_allUIGestureRecognizerBlockTargets {
NSMutableArray *targets = objc_getAssociatedObject(self, &block_key);
if (!targets) {
targets = [NSMutableArray array];
objc_setAssociatedObject(self, &block_key, targets, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return targets;
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIGestureRecognizer+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 470
|
```objective-c
//
// UITextField+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 14/5/12.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provides extensions for `UITextField`.
*/
@interface UITextField (YYAdd)
/**
Set all text selected.
*/
- (void)selectAllText;
/**
Set text in range selected.
@param range The range of selected text in a document.
*/
- (void)setSelectedRange:(NSRange)range;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UITextField+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 146
|
```objective-c
//
// UITableView+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 14/5/12.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provides extensions for `UITableView`.
*/
@interface UITableView (YYAdd)
/**
Perform a series of method calls that insert, delete, or select rows and
sections of the receiver.
@discussion Perform a series of method calls that insert, delete, or select
rows and sections of the table. Call this method if you want
subsequent insertions, deletion, and selection operations (for
example, cellForRowAtIndexPath: and indexPathsForVisibleRows)
to be animated simultaneously.
@discussion If you do not make the insertion, deletion, and selection calls
inside this block, table attributes such as row count might become
invalid. You should not call reloadData within the block; if you
call this method within the group, you will need to perform any
animations yourself.
@param block A block combine a series of method calls.
*/
- (void)updateWithBlock:(void (^)(UITableView *tableView))block;
/**
Scrolls the receiver until a row or section location on the screen.
@discussion Invoking this method does not cause the delegate to
receive a scrollViewDidScroll: message, as is normal for
programmatically-invoked user interface operations.
@param row Row index in section. NSNotFound is a valid value for
scrolling to a section with zero rows.
@param section Section index in table.
@param scrollPosition A constant that identifies a relative position in the
receiving table view (top, middle, bottom) for row when
scrolling concludes.
@param animated YES if you want to animate the change in position,
NO if it should be immediate.
*/
- (void)scrollToRow:(NSUInteger)row inSection:(NSUInteger)section atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated;
/**
Inserts a row in the receiver with an option to animate the insertion.
@param row Row index in section.
@param section Section index in table.
@param animation A constant that either specifies the kind of animation to
perform when inserting the cell or requests no animation.
*/
- (void)insertRow:(NSUInteger)row inSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation;
/**
Reloads the specified row using a certain animation effect.
@param row Row index in section.
@param section Section index in table.
@param animation A constant that indicates how the reloading is to be animated,
for example, fade out or slide out from the bottom. The animation
constant affects the direction in which both the old and the
new rows slide. For example, if the animation constant is
UITableViewRowAnimationRight, the old rows slide out to the
right and the new cells slide in from the right.
*/
- (void)reloadRow:(NSUInteger)row inSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation;
/**
Deletes the row with an option to animate the deletion.
@param row Row index in section.
@param section Section index in table.
@param animation A constant that indicates how the deletion is to be animated,
for example, fade out or slide out from the bottom.
*/
- (void)deleteRow:(NSUInteger)row inSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation;
/**
Inserts the row in the receiver at the locations identified by the indexPath,
with an option to animate the insertion.
@param indexPath An NSIndexPath object representing a row index and section
index that together identify a row in the table view.
@param animation A constant that either specifies the kind of animation to
perform when inserting the cell or requests no animation.
*/
- (void)insertRowAtIndexPath:(NSIndexPath *)indexPath withRowAnimation:(UITableViewRowAnimation)animation;
/**
Reloads the specified row using a certain animation effect.
@param indexPath An NSIndexPath object representing a row index and section
index that together identify a row in the table view.
@param animation A constant that indicates how the reloading is to be animated,
for example, fade out or slide out from the bottom. The animation
constant affects the direction in which both the old and the
new rows slide. For example, if the animation constant is
UITableViewRowAnimationRight, the old rows slide out to the
right and the new cells slide in from the right.
*/
- (void)reloadRowAtIndexPath:(NSIndexPath *)indexPath withRowAnimation:(UITableViewRowAnimation)animation;
/**
Deletes the row specified by an array of index paths,
with an option to animate the deletion.
@param indexPath An NSIndexPath object representing a row index and section
index that together identify a row in the table view.
@param animation A constant that indicates how the deletion is to be animated,
for example, fade out or slide out from the bottom.
*/
- (void)deleteRowAtIndexPath:(NSIndexPath *)indexPath withRowAnimation:(UITableViewRowAnimation)animation;
/**
Inserts a section in the receiver, with an option to animate the insertion.
@param section An index specifies the section to insert in the receiving
table view. If a section already exists at the specified
index location, it is moved down one index location.
@param animation A constant that indicates how the insertion is to be animated,
for example, fade in or slide in from the left.
*/
- (void)insertSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation;
/**
Deletes a section in the receiver, with an option to animate the deletion.
@param section An index that specifies the sections to delete from the
receiving table view. If a section exists after the specified
index location, it is moved up one index location.
@param animation A constant that either specifies the kind of animation to
perform when deleting the section or requests no animation.
*/
- (void)deleteSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation;
/**
Reloads the specified section using a given animation effect.
@param section An index identifying the section to reload.
@param animation A constant that indicates how the reloading is to be animated,
for example, fade out or slide out from the bottom. The
animation constant affects the direction in which both the
old and the new section rows slide. For example, if the
animation constant is UITableViewRowAnimationRight, the old
rows slide out to the right and the new cells slide in from the right.
*/
- (void)reloadSection:(NSUInteger)section withRowAnimation:(UITableViewRowAnimation)animation;
/**
Unselect all rows in tableView.
@param animated YES to animate the transition, NO to make the transition immediate.
*/
- (void)clearSelectedRowsAnimated:(BOOL)animated;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UITableView+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,482
|
```objective-c
//
// UIBezierPath+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 14/10/30.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provides extensions for `UIBezierPath`.
*/
@interface UIBezierPath (YYAdd)
/**
Creates and returns a new UIBezierPath object initialized with the text glyphs
generated from the specified font.
@discussion It doesnot support apple emoji. If you want get emoji image, try
[UIImage imageWithEmoji:size:] in `UIImage(YYAdd)`.
@param text The text to generate glyph path.
@param font The font to generate glyph path.
@return A new path object with the text and font, or nil if an error occurs.
*/
+ (nullable UIBezierPath *)bezierPathWithText:(NSString *)text font:(UIFont *)font;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIBezierPath+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 223
|
```objective-c
//
// UIColor+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 13/4/4.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "UIColor+YYAdd.h"
#import "NSString+YYAdd.h"
#import "YYKitMacro.h"
YYSYNTH_DUMMY_CLASS(UIColor_YYAdd)
#define CLAMP_COLOR_VALUE(v) (v) = (v) < 0 ? 0 : (v) > 1 ? 1 : (v)
void YY_RGB2HSL(CGFloat r, CGFloat g, CGFloat b,
CGFloat *h, CGFloat *s, CGFloat *l) {
CLAMP_COLOR_VALUE(r);
CLAMP_COLOR_VALUE(g);
CLAMP_COLOR_VALUE(b);
CGFloat max, min, delta, sum;
max = fmaxf(r, fmaxf(g, b));
min = fminf(r, fminf(g, b));
delta = max - min;
sum = max + min;
*l = sum / 2; // Lightness
if (delta == 0) { // No Saturation, so Hue is undefined (achromatic)
*h = *s = 0;
return;
}
*s = delta / (sum < 1 ? sum : 2 - sum); // Saturation
if (r == max) *h = (g - b) / delta / 6; // color between y & m
else if (g == max) *h = (2 + (b - r) / delta) / 6; // color between c & y
else *h = (4 + (r - g) / delta) / 6; // color between m & y
if (*h < 0) *h += 1;
}
void YY_HSL2RGB(CGFloat h, CGFloat s, CGFloat l,
CGFloat *r, CGFloat *g, CGFloat *b) {
CLAMP_COLOR_VALUE(h);
CLAMP_COLOR_VALUE(s);
CLAMP_COLOR_VALUE(l);
if (s == 0) { // No Saturation, Hue is undefined (achromatic)
*r = *g = *b = l;
return;
}
CGFloat q;
q = (l <= 0.5) ? (l * (1 + s)) : (l + s - (l * s));
if (q <= 0) {
*r = *g = *b = 0.0;
} else {
*r = *g = *b = 0;
int sextant;
CGFloat m, sv, fract, vsf, mid1, mid2;
m = l + l - q;
sv = (q - m) / q;
if (h == 1) h = 0;
h *= 6.0;
sextant = h;
fract = h - sextant;
vsf = q * sv * fract;
mid1 = m + vsf;
mid2 = q - vsf;
switch (sextant) {
case 0: *r = q; *g = mid1; *b = m; break;
case 1: *r = mid2; *g = q; *b = m; break;
case 2: *r = m; *g = q; *b = mid1; break;
case 3: *r = m; *g = mid2; *b = q; break;
case 4: *r = mid1; *g = m; *b = q; break;
case 5: *r = q; *g = m; *b = mid2; break;
}
}
}
void YY_RGB2HSB(CGFloat r, CGFloat g, CGFloat b,
CGFloat *h, CGFloat *s, CGFloat *v) {
CLAMP_COLOR_VALUE(r);
CLAMP_COLOR_VALUE(g);
CLAMP_COLOR_VALUE(b);
CGFloat max, min, delta;
max = fmax(r, fmax(g, b));
min = fmin(r, fmin(g, b));
delta = max - min;
*v = max; // Brightness
if (delta == 0) { // No Saturation, so Hue is undefined (achromatic)
*h = *s = 0;
return;
}
*s = delta / max; // Saturation
if (r == max) *h = (g - b) / delta / 6; // color between y & m
else if (g == max) *h = (2 + (b - r) / delta) / 6; // color between c & y
else *h = (4 + (r - g) / delta) / 6; // color between m & c
if (*h < 0) *h += 1;
}
void YY_HSB2RGB(CGFloat h, CGFloat s, CGFloat v,
CGFloat *r, CGFloat *g, CGFloat *b) {
CLAMP_COLOR_VALUE(h);
CLAMP_COLOR_VALUE(s);
CLAMP_COLOR_VALUE(v);
if (s == 0) {
*r = *g = *b = v; // No Saturation, so Hue is undefined (Achromatic)
} else {
int sextant;
CGFloat f, p, q, t;
if (h == 1) h = 0;
h *= 6;
sextant = floor(h);
f = h - sextant;
p = v * (1 - s);
q = v * (1 - s * f);
t = v * (1 - s * (1 - f));
switch (sextant) {
case 0: *r = v; *g = t; *b = p; break;
case 1: *r = q; *g = v; *b = p; break;
case 2: *r = p; *g = v; *b = t; break;
case 3: *r = p; *g = q; *b = v; break;
case 4: *r = t; *g = p; *b = v; break;
case 5: *r = v; *g = p; *b = q; break;
}
}
}
void YY_RGB2CMYK(CGFloat r, CGFloat g, CGFloat b,
CGFloat *c, CGFloat *m, CGFloat *y, CGFloat *k) {
CLAMP_COLOR_VALUE(r);
CLAMP_COLOR_VALUE(g);
CLAMP_COLOR_VALUE(b);
*c = 1 - r;
*m = 1 - g;
*y = 1 - b;
*k = fmin(*c, fmin(*m, *y));
if (*k == 1) {
*c = *m = *y = 0; // Pure black
} else {
*c = (*c - *k) / (1 - *k);
*m = (*m - *k) / (1 - *k);
*y = (*y - *k) / (1 - *k);
}
}
void YY_CMYK2RGB(CGFloat c, CGFloat m, CGFloat y, CGFloat k,
CGFloat *r, CGFloat *g, CGFloat *b) {
CLAMP_COLOR_VALUE(c);
CLAMP_COLOR_VALUE(m);
CLAMP_COLOR_VALUE(y);
CLAMP_COLOR_VALUE(k);
*r = (1 - c) * (1 - k);
*g = (1 - m) * (1 - k);
*b = (1 - y) * (1 - k);
}
void YY_HSB2HSL(CGFloat h, CGFloat s, CGFloat b,
CGFloat *hh, CGFloat *ss, CGFloat *ll) {
CLAMP_COLOR_VALUE(h);
CLAMP_COLOR_VALUE(s);
CLAMP_COLOR_VALUE(b);
*hh = h;
*ll = (2 - s) * b / 2;
if (*ll <= 0.5) {
*ss = (s) / ((2 - s));
} else {
*ss = (s * b) / (2 - (2 - s) * b);
}
}
void YY_HSL2HSB(CGFloat h, CGFloat s, CGFloat l,
CGFloat *hh, CGFloat *ss, CGFloat *bb) {
CLAMP_COLOR_VALUE(h);
CLAMP_COLOR_VALUE(s);
CLAMP_COLOR_VALUE(l);
*hh = h;
if (l <= 0.5) {
*bb = (s + 1) * l;
*ss = (2 * s) / (s + 1);
} else {
*bb = l + s * (1 - l);
*ss = (2 * s * (1 - l)) / *bb;
}
}
#undef CLAMP_COLOR_VALUE
@implementation UIColor (YYAdd)
+ (UIColor *)colorWithHue:(CGFloat)hue
saturation:(CGFloat)saturation
lightness:(CGFloat)lightness
alpha:(CGFloat)alpha {
CGFloat r, g, b;
YY_HSL2RGB(hue, saturation, lightness, &r, &g, &b);
return [UIColor colorWithRed:r green:g blue:b alpha:alpha];
}
+ (UIColor *)colorWithCyan:(CGFloat)cyan
magenta:(CGFloat)magenta
yellow:(CGFloat)yellow
black:(CGFloat)black
alpha:(CGFloat)alpha {
CGFloat r, g, b;
YY_CMYK2RGB(cyan, magenta, yellow, black, &r, &g, &b);
return [UIColor colorWithRed:r green:g blue:b alpha:alpha];
}
+ (UIColor *)colorWithRGB:(uint32_t)rgbValue {
return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16) / 255.0f
green:((rgbValue & 0xFF00) >> 8) / 255.0f
blue:(rgbValue & 0xFF) / 255.0f
alpha:1];
}
+ (UIColor *)colorWithRGBA:(uint32_t)rgbaValue {
return [UIColor colorWithRed:((rgbaValue & 0xFF000000) >> 24) / 255.0f
green:((rgbaValue & 0xFF0000) >> 16) / 255.0f
blue:((rgbaValue & 0xFF00) >> 8) / 255.0f
alpha:(rgbaValue & 0xFF) / 255.0f];
}
+ (UIColor *)colorWithRGB:(uint32_t)rgbValue alpha:(CGFloat)alpha {
return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16) / 255.0f
green:((rgbValue & 0xFF00) >> 8) / 255.0f
blue:(rgbValue & 0xFF) / 255.0f
alpha:alpha];
}
- (uint32_t)rgbValue {
CGFloat r = 0, g = 0, b = 0, a = 0;
[self getRed:&r green:&g blue:&b alpha:&a];
int8_t red = r * 255;
uint8_t green = g * 255;
uint8_t blue = b * 255;
return (red << 16) + (green << 8) + blue;
}
- (uint32_t)rgbaValue {
CGFloat r = 0, g = 0, b = 0, a = 0;
[self getRed:&r green:&g blue:&b alpha:&a];
int8_t red = r * 255;
uint8_t green = g * 255;
uint8_t blue = b * 255;
uint8_t alpha = a * 255;
return (red << 24) + (green << 16) + (blue << 8) + alpha;
}
static inline NSUInteger hexStrToInt(NSString *str) {
uint32_t result = 0;
sscanf([str UTF8String], "%X", &result);
return result;
}
static BOOL hexStrToRGBA(NSString *str,
CGFloat *r, CGFloat *g, CGFloat *b, CGFloat *a) {
str = [[str stringByTrim] uppercaseString];
if ([str hasPrefix:@"#"]) {
str = [str substringFromIndex:1];
} else if ([str hasPrefix:@"0X"]) {
str = [str substringFromIndex:2];
}
NSUInteger length = [str length];
// RGB RGBA RRGGBB RRGGBBAA
if (length != 3 && length != 4 && length != 6 && length != 8) {
return NO;
}
//RGB,RGBA,RRGGBB,RRGGBBAA
if (length < 5) {
*r = hexStrToInt([str substringWithRange:NSMakeRange(0, 1)]) / 255.0f;
*g = hexStrToInt([str substringWithRange:NSMakeRange(1, 1)]) / 255.0f;
*b = hexStrToInt([str substringWithRange:NSMakeRange(2, 1)]) / 255.0f;
if (length == 4) *a = hexStrToInt([str substringWithRange:NSMakeRange(3, 1)]) / 255.0f;
else *a = 1;
} else {
*r = hexStrToInt([str substringWithRange:NSMakeRange(0, 2)]) / 255.0f;
*g = hexStrToInt([str substringWithRange:NSMakeRange(2, 2)]) / 255.0f;
*b = hexStrToInt([str substringWithRange:NSMakeRange(4, 2)]) / 255.0f;
if (length == 8) *a = hexStrToInt([str substringWithRange:NSMakeRange(6, 2)]) / 255.0f;
else *a = 1;
}
return YES;
}
+ (instancetype)colorWithHexString:(NSString *)hexStr {
CGFloat r, g, b, a;
if (hexStrToRGBA(hexStr, &r, &g, &b, &a)) {
return [UIColor colorWithRed:r green:g blue:b alpha:a];
}
return nil;
}
- (NSString *)hexString {
return [self hexStringWithAlpha:NO];
}
- (NSString *)hexStringWithAlpha {
return [self hexStringWithAlpha:YES];
}
- (NSString *)hexStringWithAlpha:(BOOL)withAlpha {
CGColorRef color = self.CGColor;
size_t count = CGColorGetNumberOfComponents(color);
const CGFloat *components = CGColorGetComponents(color);
static NSString *stringFormat = @"%02x%02x%02x";
NSString *hex = nil;
if (count == 2) {
NSUInteger white = (NSUInteger)(components[0] * 255.0f);
hex = [NSString stringWithFormat:stringFormat, white, white, white];
} else if (count == 4) {
hex = [NSString stringWithFormat:stringFormat,
(NSUInteger)(components[0] * 255.0f),
(NSUInteger)(components[1] * 255.0f),
(NSUInteger)(components[2] * 255.0f)];
}
if (hex && withAlpha) {
hex = [hex stringByAppendingFormat:@"%02lx",
(unsigned long)(self.alpha * 255.0 + 0.5)];
}
return hex;
}
- (UIColor *)colorByAddColor:(UIColor *)add blendMode:(CGBlendMode)blendMode {
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big;
uint8_t pixel[4] = { 0 };
CGContextRef context = CGBitmapContextCreate(&pixel, 1, 1, 8, 4, colorSpace, bitmapInfo);
CGContextSetFillColorWithColor(context, self.CGColor);
CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
CGContextSetBlendMode(context, blendMode);
CGContextSetFillColorWithColor(context, add.CGColor);
CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
return [UIColor colorWithRed:pixel[0] / 255.0f green:pixel[1] / 255.0f blue:pixel[2] / 255.0f alpha:pixel[3] / 255.0f];
}
- (UIColor *)colorByChangeHue:(CGFloat)h saturation:(CGFloat)s brightness:(CGFloat)b alpha:(CGFloat)a {
CGFloat hh, ss, bb, aa;
if (![self getHue:&hh saturation:&ss brightness:&bb alpha:&aa]) {
return self;
}
hh += h;
ss += s;
bb += b;
aa += a;
hh -= (int)hh;
hh = hh < 0 ? hh + 1 : hh;
ss = ss < 0 ? 0 : ss > 1 ? 1 : ss;
bb = bb < 0 ? 0 : bb > 1 ? 1 : bb;
aa = aa < 0 ? 0 : aa > 1 ? 1 : aa;
return [UIColor colorWithHue:hh saturation:ss brightness:bb alpha:aa];
}
- (BOOL)getHue:(CGFloat *)hue
saturation:(CGFloat *)saturation
lightness:(CGFloat *)lightness
alpha:(CGFloat *)alpha {
CGFloat r, g, b, a;
if (![self getRed:&r green:&g blue:&b alpha:&a]) {
return NO;
}
YY_RGB2HSL(r, g, b, hue, saturation, lightness);
*alpha = a;
return YES;
}
- (BOOL)getCyan:(CGFloat *)cyan
magenta:(CGFloat *)magenta
yellow:(CGFloat *)yellow
black:(CGFloat *)black
alpha:(CGFloat *)alpha {
CGFloat r, g, b, a;
if (![self getRed:&r green:&g blue:&b alpha:&a]) {
return NO;
}
YY_RGB2CMYK(r, g, b, cyan, magenta, yellow, black);
*alpha = a;
return YES;
}
- (CGFloat)red {
CGFloat r = 0, g, b, a;
[self getRed:&r green:&g blue:&b alpha:&a];
return r;
}
- (CGFloat)green {
CGFloat r, g = 0, b, a;
[self getRed:&r green:&g blue:&b alpha:&a];
return g;
}
- (CGFloat)blue {
CGFloat r, g, b = 0, a;
[self getRed:&r green:&g blue:&b alpha:&a];
return b;
}
- (CGFloat)alpha {
return CGColorGetAlpha(self.CGColor);
}
- (CGFloat)hue {
CGFloat h = 0, s, b, a;
[self getHue:&h saturation:&s brightness:&b alpha:&a];
return h;
}
- (CGFloat)saturation {
CGFloat h, s = 0, b, a;
[self getHue:&h saturation:&s brightness:&b alpha:&a];
return s;
}
- (CGFloat)brightness {
CGFloat h, s, b = 0, a;
[self getHue:&h saturation:&s brightness:&b alpha:&a];
return b;
}
- (CGColorSpaceModel)colorSpaceModel {
return CGColorSpaceGetModel(CGColorGetColorSpace(self.CGColor));
}
- (NSString *)colorSpaceString {
CGColorSpaceModel model = CGColorSpaceGetModel(CGColorGetColorSpace(self.CGColor));
switch (model) {
case kCGColorSpaceModelUnknown:
return @"kCGColorSpaceModelUnknown";
case kCGColorSpaceModelMonochrome:
return @"kCGColorSpaceModelMonochrome";
case kCGColorSpaceModelRGB:
return @"kCGColorSpaceModelRGB";
case kCGColorSpaceModelCMYK:
return @"kCGColorSpaceModelCMYK";
case kCGColorSpaceModelLab:
return @"kCGColorSpaceModelLab";
case kCGColorSpaceModelDeviceN:
return @"kCGColorSpaceModelDeviceN";
case kCGColorSpaceModelIndexed:
return @"kCGColorSpaceModelIndexed";
case kCGColorSpaceModelPattern:
return @"kCGColorSpaceModelPattern";
default:
return @"ColorSpaceInvalid";
}
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIColor+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 4,611
|
```objective-c
//
// UIView+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 13/4/3.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provides extensions for `UIView`.
*/
@interface UIView (YYAdd)
/**
Create a snapshot image of the complete view hierarchy.
*/
- (nullable UIImage *)snapshotImage;
/**
Create a snapshot image of the complete view hierarchy.
@discussion It's faster than "snapshotImage", but may cause screen updates.
See -[UIView drawViewHierarchyInRect:afterScreenUpdates:] for more information.
*/
- (nullable UIImage *)snapshotImageAfterScreenUpdates:(BOOL)afterUpdates;
/**
Create a snapshot PDF of the complete view hierarchy.
*/
- (nullable NSData *)snapshotPDF;
/**
Shortcut to set the view.layer's shadow
@param color Shadow Color
@param offset Shadow offset
@param radius Shadow radius
*/
- (void)setLayerShadow:(nullable UIColor*)color offset:(CGSize)offset radius:(CGFloat)radius;
/**
Remove all subviews.
@warning Never call this method inside your view's drawRect: method.
*/
- (void)removeAllSubviews;
/**
Returns the view's view controller (may be nil).
*/
@property (nullable, nonatomic, readonly) UIViewController *viewController;
/**
Returns the visible alpha on screen, taking into account superview and window.
*/
@property (nonatomic, readonly) CGFloat visibleAlpha;
/**
Converts a point from the receiver's coordinate system to that of the specified view or window.
@param point A point specified in the local coordinate system (bounds) of the receiver.
@param view The view or window into whose coordinate system point is to be converted.
If view is nil, this method instead converts to window base coordinates.
@return The point converted to the coordinate system of view.
*/
- (CGPoint)convertPoint:(CGPoint)point toViewOrWindow:(nullable UIView *)view;
/**
Converts a point from the coordinate system of a given view or window to that of the receiver.
@param point A point specified in the local coordinate system (bounds) of view.
@param view The view or window with point in its coordinate system.
If view is nil, this method instead converts from window base coordinates.
@return The point converted to the local coordinate system (bounds) of the receiver.
*/
- (CGPoint)convertPoint:(CGPoint)point fromViewOrWindow:(nullable UIView *)view;
/**
Converts a rectangle from the receiver's coordinate system to that of another view or window.
@param rect A rectangle specified in the local coordinate system (bounds) of the receiver.
@param view The view or window that is the target of the conversion operation. If view is nil, this method instead converts to window base coordinates.
@return The converted rectangle.
*/
- (CGRect)convertRect:(CGRect)rect toViewOrWindow:(nullable UIView *)view;
/**
Converts a rectangle from the coordinate system of another view or window to that of the receiver.
@param rect A rectangle specified in the local coordinate system (bounds) of view.
@param view The view or window with rect in its coordinate system.
If view is nil, this method instead converts from window base coordinates.
@return The converted rectangle.
*/
- (CGRect)convertRect:(CGRect)rect fromViewOrWindow:(nullable UIView *)view;
@property (nonatomic) CGFloat left; ///< Shortcut for frame.origin.x.
@property (nonatomic) CGFloat top; ///< Shortcut for frame.origin.y
@property (nonatomic) CGFloat right; ///< Shortcut for frame.origin.x + frame.size.width
@property (nonatomic) CGFloat bottom; ///< Shortcut for frame.origin.y + frame.size.height
@property (nonatomic) CGFloat width; ///< Shortcut for frame.size.width.
@property (nonatomic) CGFloat height; ///< Shortcut for frame.size.height.
@property (nonatomic) CGFloat centerX; ///< Shortcut for center.x
@property (nonatomic) CGFloat centerY; ///< Shortcut for center.y
@property (nonatomic) CGPoint origin; ///< Shortcut for frame.origin.
@property (nonatomic) CGSize size; ///< Shortcut for frame.size.
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIView+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 889
|
```objective-c
//
// UIBezierPath+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 14/10/30.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "UIBezierPath+YYAdd.h"
#import "UIFont+YYAdd.h"
#import <CoreText/CoreText.h>
#import "YYKitMacro.h"
YYSYNTH_DUMMY_CLASS(UIBezierPath_YYAdd)
@implementation UIBezierPath (YYAdd)
+ (UIBezierPath *)bezierPathWithText:(NSString *)text font:(UIFont *)font {
CTFontRef ctFont = font.CTFontRef;
if (!ctFont) return nil;
NSDictionary *attrs = @{ (__bridge id)kCTFontAttributeName:(__bridge id)ctFont };
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:text attributes:attrs];
CFRelease(ctFont);
CTLineRef line = CTLineCreateWithAttributedString((__bridge CFTypeRef)attrString);
if (!line) return nil;
CGMutablePathRef cgPath = CGPathCreateMutable();
CFArrayRef runs = CTLineGetGlyphRuns(line);
for (CFIndex iRun = 0, iRunMax = CFArrayGetCount(runs); iRun < iRunMax; iRun++) {
CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, iRun);
CTFontRef runFont = CFDictionaryGetValue(CTRunGetAttributes(run), kCTFontAttributeName);
for (CFIndex iGlyph = 0, iGlyphMax = CTRunGetGlyphCount(run); iGlyph < iGlyphMax; iGlyph++) {
CFRange glyphRange = CFRangeMake(iGlyph, 1);
CGGlyph glyph;
CGPoint position;
CTRunGetGlyphs(run, glyphRange, &glyph);
CTRunGetPositions(run, glyphRange, &position);
CGPathRef glyphPath = CTFontCreatePathForGlyph(runFont, glyph, NULL);
if (glyphPath) {
CGAffineTransform transform = CGAffineTransformMakeTranslation(position.x, position.y);
CGPathAddPath(cgPath, &transform, glyphPath);
CGPathRelease(glyphPath);
}
}
}
UIBezierPath *path = [UIBezierPath bezierPathWithCGPath:cgPath];
CGRect boundingBox = CGPathGetPathBoundingBox(cgPath);
CFRelease(cgPath);
CFRelease(line);
[path applyTransform:CGAffineTransformMakeScale(1.0, -1.0)];
[path applyTransform:CGAffineTransformMakeTranslation(0.0, boundingBox.size.height)];
return path;
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIBezierPath+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 597
|
```objective-c
//
// UIImage+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 13/4/4.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provide some commen method for `UIImage`.
Image process is based on CoreGraphic and vImage.
*/
@interface UIImage (YYAdd)
#pragma mark - Create image
///=============================================================================
/// @name Create image
///=============================================================================
/**
Create an animated image with GIF data. After created, you can access
the images via property '.images'. If the data is not animated gif, this
function is same as [UIImage imageWithData:data scale:scale];
@discussion It has a better display performance, but costs more memory
(width * height * frames Bytes). It only suited to display small
gif such as animated emoticon. If you want to display large gif,
see `YYImage`.
@param data GIF data.
@param scale The scale factor
@return A new image created from GIF, or nil when an error occurs.
*/
+ (nullable UIImage *)imageWithSmallGIFData:(NSData *)data scale:(CGFloat)scale;
/**
Whether the data is animated GIF.
@param data Image data
@return Returns YES only if the data is gif and contains more than one frame,
otherwise returns NO.
*/
+ (BOOL)isAnimatedGIFData:(NSData *)data;
/**
Whether the file in the specified path is GIF.
@param path An absolute file path.
@return Returns YES if the file is gif, otherwise returns NO.
*/
+ (BOOL)isAnimatedGIFFile:(NSString *)path;
/**
Create an image from a PDF file data or path.
@discussion If the PDF has multiple page, is just return's the first page's
content. Image's scale is equal to current screen's scale, size is same as
PDF's origin size.
@param dataOrPath PDF data in `NSData`, or PDF file path in `NSString`.
@return A new image create from PDF, or nil when an error occurs.
*/
+ (nullable UIImage *)imageWithPDF:(id)dataOrPath;
/**
Create an image from a PDF file data or path.
@discussion If the PDF has multiple page, is just return's the first page's
content. Image's scale is equal to current screen's scale.
@param dataOrPath PDF data in `NSData`, or PDF file path in `NSString`.
@param size The new image's size, PDF's content will be stretched as needed.
@return A new image create from PDF, or nil when an error occurs.
*/
+ (nullable UIImage *)imageWithPDF:(id)dataOrPath size:(CGSize)size;
/**
Create a square image from apple emoji.
@discussion It creates a square image from apple emoji, image's scale is equal
to current screen's scale. The original emoji image in `AppleColorEmoji` font
is in size 160*160 px.
@param emoji single emoji, such as @"".
@param size image's size.
@return Image from emoji, or nil when an error occurs.
*/
+ (nullable UIImage *)imageWithEmoji:(NSString *)emoji size:(CGFloat)size;
/**
Create and return a 1x1 point size image with the given color.
@param color The color.
*/
+ (nullable UIImage *)imageWithColor:(UIColor *)color;
/**
Create and return a pure color image with the given color and size.
@param color The color.
@param size New image's type.
*/
+ (nullable UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size;
/**
Create and return an image with custom draw code.
@param size The image size.
@param drawBlock The draw block.
@return The new image.
*/
+ (nullable UIImage *)imageWithSize:(CGSize)size drawBlock:(void (^)(CGContextRef context))drawBlock;
#pragma mark - Image Info
///=============================================================================
/// @name Image Info
///=============================================================================
/**
Whether this image has alpha channel.
*/
- (BOOL)hasAlphaChannel;
#pragma mark - Modify Image
///=============================================================================
/// @name Modify Image
///=============================================================================
/**
Draws the entire image in the specified rectangle, content changed with
the contentMode.
@discussion This method draws the entire image in the current graphics context,
respecting the image's orientation setting. In the default coordinate system,
images are situated down and to the right of the origin of the specified
rectangle. This method respects any transforms applied to the current graphics
context, however.
@param rect The rectangle in which to draw the image.
@param contentMode Draw content mode
@param clips A Boolean value that determines whether content are confined to the rect.
*/
- (void)drawInRect:(CGRect)rect withContentMode:(UIViewContentMode)contentMode clipsToBounds:(BOOL)clips;
/**
Returns a new image which is scaled from this image.
The image will be stretched as needed.
@param size The new size to be scaled, values should be positive.
@return The new image with the given size.
*/
- (nullable UIImage *)imageByResizeToSize:(CGSize)size;
/**
Returns a new image which is scaled from this image.
The image content will be changed with thencontentMode.
@param size The new size to be scaled, values should be positive.
@param contentMode The content mode for image content.
@return The new image with the given size.
*/
- (nullable UIImage *)imageByResizeToSize:(CGSize)size contentMode:(UIViewContentMode)contentMode;
/**
Returns a new image which is cropped from this image.
@param rect Image's inner rect.
@return The new image, or nil if an error occurs.
*/
- (nullable UIImage *)imageByCropToRect:(CGRect)rect;
/**
Returns a new image which is edge inset from this image.
@param insets Inset (positive) for each of the edges, values can be negative to 'outset'.
@param color Extend edge's fill color, nil means clear color.
@return The new image, or nil if an error occurs.
*/
- (nullable UIImage *)imageByInsetEdge:(UIEdgeInsets)insets withColor:(nullable UIColor *)color;
/**
Rounds a new image with a given corner size.
@param radius The radius of each corner oval. Values larger than half the
rectangle's width or height are clamped appropriately to half
the width or height.
*/
- (nullable UIImage *)imageByRoundCornerRadius:(CGFloat)radius;
/**
Rounds a new image with a given corner size.
@param radius The radius of each corner oval. Values larger than half the
rectangle's width or height are clamped appropriately to
half the width or height.
@param borderWidth The inset border line width. Values larger than half the rectangle's
width or height are clamped appropriately to half the width
or height.
@param borderColor The border stroke color. nil means clear color.
*/
- (nullable UIImage *)imageByRoundCornerRadius:(CGFloat)radius
borderWidth:(CGFloat)borderWidth
borderColor:(nullable UIColor *)borderColor;
/**
Rounds a new image with a given corner size.
@param radius The radius of each corner oval. Values larger than half the
rectangle's width or height are clamped appropriately to
half the width or height.
@param corners A bitmask value that identifies the corners that you want
rounded. You can use this parameter to round only a subset
of the corners of the rectangle.
@param borderWidth The inset border line width. Values larger than half the rectangle's
width or height are clamped appropriately to half the width
or height.
@param borderColor The border stroke color. nil means clear color.
@param borderLineJoin The border line join.
*/
- (nullable UIImage *)imageByRoundCornerRadius:(CGFloat)radius
corners:(UIRectCorner)corners
borderWidth:(CGFloat)borderWidth
borderColor:(nullable UIColor *)borderColor
borderLineJoin:(CGLineJoin)borderLineJoin;
/**
Returns a new rotated image (relative to the center).
@param radians Rotated radians in counterclockwise.
@param fitSize YES: new image's size is extend to fit all content.
NO: image's size will not change, content may be clipped.
*/
- (nullable UIImage *)imageByRotate:(CGFloat)radians fitSize:(BOOL)fitSize;
/**
Returns a new image rotated counterclockwise by a quarterturn (90).
The width and height will be exchanged.
*/
- (nullable UIImage *)imageByRotateLeft90;
/**
Returns a new image rotated clockwise by a quarterturn (90).
The width and height will be exchanged.
*/
- (nullable UIImage *)imageByRotateRight90;
/**
Returns a new image rotated 180 .
*/
- (nullable UIImage *)imageByRotate180;
/**
Returns a vertically flipped image.
*/
- (nullable UIImage *)imageByFlipVertical;
/**
Returns a horizontally flipped image.
*/
- (nullable UIImage *)imageByFlipHorizontal;
#pragma mark - Image Effect
///=============================================================================
/// @name Image Effect
///=============================================================================
/**
Tint the image in alpha channel with the given color.
@param color The color.
*/
- (nullable UIImage *)imageByTintColor:(UIColor *)color;
/**
Returns a grayscaled image.
*/
- (nullable UIImage *)imageByGrayscale;
/**
Applies a blur effect to this image. Suitable for blur any content.
*/
- (nullable UIImage *)imageByBlurSoft;
/**
Applies a blur effect to this image. Suitable for blur any content except pure white.
(same as iOS Control Panel)
*/
- (nullable UIImage *)imageByBlurLight;
/**
Applies a blur effect to this image. Suitable for displaying black text.
(same as iOS Navigation Bar White)
*/
- (nullable UIImage *)imageByBlurExtraLight;
/**
Applies a blur effect to this image. Suitable for displaying white text.
(same as iOS Notification Center)
*/
- (nullable UIImage *)imageByBlurDark;
/**
Applies a blur and tint color to this image.
@param tintColor The tint color.
*/
- (nullable UIImage *)imageByBlurWithTint:(UIColor *)tintColor;
/**
Applies a blur, tint color, and saturation adjustment to this image,
optionally within the area specified by @a maskImage.
@param blurRadius The radius of the blur in points, 0 means no blur effect.
@param tintColor An optional UIColor object that is uniformly blended with
the result of the blur and saturation operations. The
alpha channel of this color determines how strong the
tint is. nil means no tint.
@param tintBlendMode The @a tintColor blend mode. Default is kCGBlendModeNormal (0).
@param saturation A value of 1.0 produces no change in the resulting image.
Values less than 1.0 will desaturation the resulting image
while values greater than 1.0 will have the opposite effect.
0 means gray scale.
@param maskImage If specified, @a inputImage is only modified in the area(s)
defined by this mask. This must be an image mask or it
must meet the requirements of the mask parameter of
CGContextClipToMask.
@return image with effect, or nil if an error occurs (e.g. no
enough memory).
*/
- (nullable UIImage *)imageByBlurRadius:(CGFloat)blurRadius
tintColor:(nullable UIColor *)tintColor
tintMode:(CGBlendMode)tintBlendMode
saturation:(CGFloat)saturation
maskImage:(nullable UIImage *)maskImage;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIImage+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 2,540
|
```objective-c
//
// UIBarButtonItem+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 13/10/15.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provides extensions for `UIBarButtonItem`.
*/
@interface UIBarButtonItem (YYAdd)
/**
The block that invoked when the item is selected. The objects captured by block
will retained by the ButtonItem.
@discussion This param is conflict with `target` and `action` property.
Set this will set `target` and `action` property to some internal objects.
*/
@property (nullable, nonatomic, copy) void (^actionBlock)(id);
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIBarButtonItem+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 171
|
```objective-c
//
// UIColor+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 13/4/4.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
extern void YY_RGB2HSL(CGFloat r, CGFloat g, CGFloat b,
CGFloat *h, CGFloat *s, CGFloat *l);
extern void YY_HSL2RGB(CGFloat h, CGFloat s, CGFloat l,
CGFloat *r, CGFloat *g, CGFloat *b);
extern void YY_RGB2HSB(CGFloat r, CGFloat g, CGFloat b,
CGFloat *h, CGFloat *s, CGFloat *v);
extern void YY_HSB2RGB(CGFloat h, CGFloat s, CGFloat v,
CGFloat *r, CGFloat *g, CGFloat *b);
extern void YY_RGB2CMYK(CGFloat r, CGFloat g, CGFloat b,
CGFloat *c, CGFloat *m, CGFloat *y, CGFloat *k);
extern void YY_CMYK2RGB(CGFloat c, CGFloat m, CGFloat y, CGFloat k,
CGFloat *r, CGFloat *g, CGFloat *b);
extern void YY_HSB2HSL(CGFloat h, CGFloat s, CGFloat b,
CGFloat *hh, CGFloat *ss, CGFloat *ll);
extern void YY_HSL2HSB(CGFloat h, CGFloat s, CGFloat l,
CGFloat *hh, CGFloat *ss, CGFloat *bb);
/*
Create UIColor with a hex string.
Example: UIColorHex(0xF0F), UIColorHex(66ccff), UIColorHex(#66CCFF88)
Valid format: #RGB #RGBA #RRGGBB #RRGGBBAA 0xRGB ...
The `#` or "0x" sign is not required.
*/
#ifndef UIColorHex
#define UIColorHex(_hex_) [UIColor colorWithHexString:((__bridge NSString *)CFSTR(#_hex_))]
#endif
/**
Provide some method for `UIColor` to convert color between
RGB,HSB,HSL,CMYK and Hex.
| Color space | Meaning |
|-------------|----------------------------------------|
| RGB * | Red, Green, Blue |
| HSB(HSV) * | Hue, Saturation, Brightness (Value) |
| HSL | Hue, Saturation, Lightness |
| CMYK | Cyan, Magenta, Yellow, Black |
Apple use RGB & HSB default.
All the value in this category is float number in the range `0.0` to `1.0`.
Values below `0.0` are interpreted as `0.0`,
and values above `1.0` are interpreted as `1.0`.
If you want convert color between more color space (CIEXYZ,Lab,YUV...),
see path_to_url
*/
@interface UIColor (YYAdd)
#pragma mark - Create a UIColor Object
///=============================================================================
/// @name Creating a UIColor Object
///=============================================================================
/**
Creates and returns a color object using the specified opacity
and HSL color space component values.
@param hue The hue component of the color object in the HSL color space,
specified as a value from 0.0 to 1.0.
@param saturation The saturation component of the color object in the HSL color space,
specified as a value from 0.0 to 1.0.
@param lightness The lightness component of the color object in the HSL color space,
specified as a value from 0.0 to 1.0.
@param alpha The opacity value of the color object,
specified as a value from 0.0 to 1.0.
@return The color object. The color information represented by this
object is in the device RGB colorspace.
*/
+ (UIColor *)colorWithHue:(CGFloat)hue
saturation:(CGFloat)saturation
lightness:(CGFloat)lightness
alpha:(CGFloat)alpha;
/**
Creates and returns a color object using the specified opacity
and CMYK color space component values.
@param cyan The cyan component of the color object in the CMYK color space,
specified as a value from 0.0 to 1.0.
@param magenta The magenta component of the color object in the CMYK color space,
specified as a value from 0.0 to 1.0.
@param yellow The yellow component of the color object in the CMYK color space,
specified as a value from 0.0 to 1.0.
@param black The black component of the color object in the CMYK color space,
specified as a value from 0.0 to 1.0.
@param alpha The opacity value of the color object,
specified as a value from 0.0 to 1.0.
@return The color object. The color information represented by this
object is in the device RGB colorspace.
*/
+ (UIColor *)colorWithCyan:(CGFloat)cyan
magenta:(CGFloat)magenta
yellow:(CGFloat)yellow
black:(CGFloat)black
alpha:(CGFloat)alpha;
/**
Creates and returns a color object using the hex RGB color values.
@param rgbValue The rgb value such as 0x66ccff.
@return The color object. The color information represented by this
object is in the device RGB colorspace.
*/
+ (UIColor *)colorWithRGB:(uint32_t)rgbValue;
/**
Creates and returns a color object using the hex RGBA color values.
@param rgbaValue The rgb value such as 0x66ccffff.
@return The color object. The color information represented by this
object is in the device RGB colorspace.
*/
+ (UIColor *)colorWithRGBA:(uint32_t)rgbaValue;
/**
Creates and returns a color object using the specified opacity and RGB hex value.
@param rgbValue The rgb value such as 0x66CCFF.
@param alpha The opacity value of the color object,
specified as a value from 0.0 to 1.0.
@return The color object. The color information represented by this
object is in the device RGB colorspace.
*/
+ (UIColor *)colorWithRGB:(uint32_t)rgbValue alpha:(CGFloat)alpha;
/**
Creates and returns a color object from hex string.
@discussion:
Valid format: #RGB #RGBA #RRGGBB #RRGGBBAA 0xRGB ...
The `#` or "0x" sign is not required.
The alpha will be set to 1.0 if there is no alpha component.
It will return nil when an error occurs in parsing.
Example: @"0xF0F", @"66ccff", @"#66CCFF88"
@param hexStr The hex string value for the new color.
@return An UIColor object from string, or nil if an error occurs.
*/
+ (nullable UIColor *)colorWithHexString:(NSString *)hexStr;
/**
Creates and returns a color object by add new color.
@param add the color added
@param blendMode add color blend mode
*/
- (UIColor *)colorByAddColor:(UIColor *)add blendMode:(CGBlendMode)blendMode;
/**
Creates and returns a color object by change components.
@param hueDelta the hue change delta specified as a value
from -1.0 to 1.0. 0 means no change.
@param saturationDelta the saturation change delta specified as a value
from -1.0 to 1.0. 0 means no change.
@param brightnessDelta the brightness change delta specified as a value
from -1.0 to 1.0. 0 means no change.
@param alphaDelta the alpha change delta specified as a value
from -1.0 to 1.0. 0 means no change.
*/
- (UIColor *)colorByChangeHue:(CGFloat)hueDelta
saturation:(CGFloat)saturationDelta
brightness:(CGFloat)brightnessDelta
alpha:(CGFloat)alphaDelta;
#pragma mark - Get color's description
///=============================================================================
/// @name Get color's description
///=============================================================================
/**
Returns the rgb value in hex.
@return hex value of RGB,such as 0x66ccff.
*/
- (uint32_t)rgbValue;
/**
Returns the rgba value in hex.
@return hex value of RGBA,such as 0x66ccffff.
*/
- (uint32_t)rgbaValue;
/**
Returns the color's RGB value as a hex string (lowercase).
Such as @"0066cc".
It will return nil when the color space is not RGB
@return The color's value as a hex string.
*/
- (nullable NSString *)hexString;
/**
Returns the color's RGBA value as a hex string (lowercase).
Such as @"0066ccff".
It will return nil when the color space is not RGBA
@return The color's value as a hex string.
*/
- (nullable NSString *)hexStringWithAlpha;
#pragma mark - Retrieving Color Information
///=============================================================================
/// @name Retrieving Color Information
///=============================================================================
/**
Returns the components that make up the color in the HSL color space.
@param hue On return, the hue component of the color object,
specified as a value between 0.0 and 1.0.
@param saturation On return, the saturation component of the color object,
specified as a value between 0.0 and 1.0.
@param lightness On return, the lightness component of the color object,
specified as a value between 0.0 and 1.0.
@param alpha On return, the alpha component of the color object,
specified as a value between 0.0 and 1.0.
@return YES if the color could be converted, NO otherwise.
*/
- (BOOL)getHue:(CGFloat *)hue
saturation:(CGFloat *)saturation
lightness:(CGFloat *)lightness
alpha:(CGFloat *)alpha;
/**
Returns the components that make up the color in the CMYK color space.
@param cyan On return, the cyan component of the color object,
specified as a value between 0.0 and 1.0.
@param magenta On return, the magenta component of the color object,
specified as a value between 0.0 and 1.0.
@param yellow On return, the yellow component of the color object,
specified as a value between 0.0 and 1.0.
@param black On return, the black component of the color object,
specified as a value between 0.0 and 1.0.
@param alpha On return, the alpha component of the color object,
specified as a value between 0.0 and 1.0.
@return YES if the color could be converted, NO otherwise.
*/
- (BOOL)getCyan:(CGFloat *)cyan
magenta:(CGFloat *)magenta
yellow:(CGFloat *)yellow
black:(CGFloat *)black
alpha:(CGFloat *)alpha;
/**
The color's red component value in RGB color space.
The value of this property is a float in the range `0.0` to `1.0`.
*/
@property (nonatomic, readonly) CGFloat red;
/**
The color's green component value in RGB color space.
The value of this property is a float in the range `0.0` to `1.0`.
*/
@property (nonatomic, readonly) CGFloat green;
/**
The color's blue component value in RGB color space.
The value of this property is a float in the range `0.0` to `1.0`.
*/
@property (nonatomic, readonly) CGFloat blue;
/**
The color's hue component value in HSB color space.
The value of this property is a float in the range `0.0` to `1.0`.
*/
@property (nonatomic, readonly) CGFloat hue;
/**
The color's saturation component value in HSB color space.
The value of this property is a float in the range `0.0` to `1.0`.
*/
@property (nonatomic, readonly) CGFloat saturation;
/**
The color's brightness component value in HSB color space.
The value of this property is a float in the range `0.0` to `1.0`.
*/
@property (nonatomic, readonly) CGFloat brightness;
/**
The color's alpha component value.
The value of this property is a float in the range `0.0` to `1.0`.
*/
@property (nonatomic, readonly) CGFloat alpha;
/**
The color's colorspace model.
*/
@property (nonatomic, readonly) CGColorSpaceModel colorSpaceModel;
/**
Readable colorspace string.
*/
@property (nullable, nonatomic, readonly) NSString *colorSpaceString;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIColor+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 2,782
|
```objective-c
//
// UIScreen+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 13/4/5.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "UIScreen+YYAdd.h"
#import "YYKitMacro.h"
#import "UIDevice+YYAdd.h"
YYSYNTH_DUMMY_CLASS(UIScreen_YYAdd);
@implementation UIScreen (YYAdd)
+ (CGFloat)screenScale {
static CGFloat screenScale = 0.0;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if ([NSThread isMainThread]) {
screenScale = [[UIScreen mainScreen] scale];
} else {
dispatch_sync(dispatch_get_main_queue(), ^{
screenScale = [[UIScreen mainScreen] scale];
});
}
});
return screenScale;
}
- (CGRect)currentBounds {
return [self boundsForOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
}
- (CGRect)boundsForOrientation:(UIInterfaceOrientation)orientation {
CGRect bounds = [self bounds];
if (UIInterfaceOrientationIsLandscape(orientation)) {
CGFloat buffer = bounds.size.width;
bounds.size.width = bounds.size.height;
bounds.size.height = buffer;
}
return bounds;
}
- (CGSize)sizeInPixel {
CGSize size = CGSizeZero;
if ([[UIScreen mainScreen] isEqual:self]) {
NSString *model = [UIDevice currentDevice].machineModel;
if ([model hasPrefix:@"iPhone"]) {
if ([model isEqualToString:@"iPhone7,1"]) return CGSizeMake(1080, 1920);
if ([model isEqualToString:@"iPhone8,2"]) return CGSizeMake(1080, 1920);
if ([model isEqualToString:@"iPhone9,2"]) return CGSizeMake(1080, 1920);
if ([model isEqualToString:@"iPhone9,4"]) return CGSizeMake(1080, 1920);
}
if ([model hasPrefix:@"iPad"]) {
if ([model hasPrefix:@"iPad6,7"]) size = CGSizeMake(2048, 2732);
if ([model hasPrefix:@"iPad6,8"]) size = CGSizeMake(2048, 2732);
}
}
if (CGSizeEqualToSize(size, CGSizeZero)) {
if ([self respondsToSelector:@selector(nativeBounds)]) {
size = self.nativeBounds.size;
} else {
size = self.bounds.size;
size.width *= self.scale;
size.height *= self.scale;
}
if (size.height < size.width) {
CGFloat tmp = size.height;
size.height = size.width;
size.width = tmp;
}
}
return size;
}
- (CGFloat)pixelsPerInch {
if (![[UIScreen mainScreen] isEqual:self]) {
return 326;
}
static CGFloat ppi = 0;
static dispatch_once_t one;
static NSString *name;
dispatch_once(&one, ^{
NSDictionary<NSString*, NSNumber *> *dic = @{
@"Watch1,1" : @326, //@"Apple Watch 38mm",
@"Watch1,2" : @326, //@"Apple Watch 43mm",
@"Watch2,3" : @326, //@"Apple Watch Series 2 38mm",
@"Watch2,4" : @326, //@"Apple Watch Series 2 42mm",
@"Watch2,6" : @326, //@"Apple Watch Series 1 38mm",
@"Watch1,7" : @326, //@"Apple Watch Series 1 42mm",
@"iPod1,1" : @163, //@"iPod touch 1",
@"iPod2,1" : @163, //@"iPod touch 2",
@"iPod3,1" : @163, //@"iPod touch 3",
@"iPod4,1" : @326, //@"iPod touch 4",
@"iPod5,1" : @326, //@"iPod touch 5",
@"iPod7,1" : @326, //@"iPod touch 6",
@"iPhone1,1" : @163, //@"iPhone 1G",
@"iPhone1,2" : @163, //@"iPhone 3G",
@"iPhone2,1" : @163, //@"iPhone 3GS",
@"iPhone3,1" : @326, //@"iPhone 4 (GSM)",
@"iPhone3,2" : @326, //@"iPhone 4",
@"iPhone3,3" : @326, //@"iPhone 4 (CDMA)",
@"iPhone4,1" : @326, //@"iPhone 4S",
@"iPhone5,1" : @326, //@"iPhone 5",
@"iPhone5,2" : @326, //@"iPhone 5",
@"iPhone5,3" : @326, //@"iPhone 5c",
@"iPhone5,4" : @326, //@"iPhone 5c",
@"iPhone6,1" : @326, //@"iPhone 5s",
@"iPhone6,2" : @326, //@"iPhone 5s",
@"iPhone7,1" : @401, //@"iPhone 6 Plus",
@"iPhone7,2" : @326, //@"iPhone 6",
@"iPhone8,1" : @326, //@"iPhone 6s",
@"iPhone8,2" : @401, //@"iPhone 6s Plus",
@"iPhone8,4" : @326, //@"iPhone SE",
@"iPhone9,1" : @326, //@"iPhone 7",
@"iPhone9,2" : @401, //@"iPhone 7 Plus",
@"iPhone9,3" : @326, //@"iPhone 7",
@"iPhone9,4" : @401, //@"iPhone 7 Plus",
@"iPad1,1" : @132, //@"iPad 1",
@"iPad2,1" : @132, //@"iPad 2 (WiFi)",
@"iPad2,2" : @132, //@"iPad 2 (GSM)",
@"iPad2,3" : @132, //@"iPad 2 (CDMA)",
@"iPad2,4" : @132, //@"iPad 2",
@"iPad2,5" : @264, //@"iPad mini 1",
@"iPad2,6" : @264, //@"iPad mini 1",
@"iPad2,7" : @264, //@"iPad mini 1",
@"iPad3,1" : @324, //@"iPad 3 (WiFi)",
@"iPad3,2" : @324, //@"iPad 3 (4G)",
@"iPad3,3" : @324, //@"iPad 3 (4G)",
@"iPad3,4" : @324, //@"iPad 4",
@"iPad3,5" : @324, //@"iPad 4",
@"iPad3,6" : @324, //@"iPad 4",
@"iPad4,1" : @324, //@"iPad Air",
@"iPad4,2" : @324, //@"iPad Air",
@"iPad4,3" : @324, //@"iPad Air",
@"iPad4,4" : @264, //@"iPad mini 2",
@"iPad4,5" : @264, //@"iPad mini 2",
@"iPad4,6" : @264, //@"iPad mini 2",
@"iPad4,7" : @264, //@"iPad mini 3",
@"iPad4,8" : @264, //@"iPad mini 3",
@"iPad4,9" : @264, //@"iPad mini 3",
@"iPad5,1" : @264, //@"iPad mini 4",
@"iPad5,2" : @264, //@"iPad mini 4",
@"iPad5,3" : @324, //@"iPad Air 2",
@"iPad5,4" : @324, //@"iPad Air 2",
@"iPad6,3" : @324, //@"iPad Pro (9.7 inch)",
@"iPad6,4" : @324, //@"iPad Pro (9.7 inch)",
@"iPad6,7" : @264, //@"iPad Pro (12.9 inch)",
@"iPad6,8" : @264, //@"iPad Pro (12.9 inch)",
};
NSString *model = [UIDevice currentDevice].machineModel;
if (model) {
ppi = dic[name].doubleValue;
}
if (ppi == 0) ppi = 326;
});
return ppi;
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIScreen+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,914
|
```objective-c
//
// UIControl+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 13/4/5.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provides extensions for `UIControl`.
*/
@interface UIControl (YYAdd)
/**
Removes all targets and actions for a particular event (or events)
from an internal dispatch table.
*/
- (void)removeAllTargets;
/**
Adds or replaces a target and action for a particular event (or events)
to an internal dispatch table.
@param target The target objectthat is, the object to which the
action message is sent. If this is nil, the responder
chain is searched for an object willing to respond to the
action message.
@param action A selector identifying an action message. It cannot be NULL.
@param controlEvents A bitmask specifying the control events for which the
action message is sent.
*/
- (void)setTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
/**
Adds a block for a particular event (or events) to an internal dispatch table.
It will cause a strong reference to @a block.
@param block The block which is invoked then the action message is
sent (cannot be nil). The block is retained.
@param controlEvents A bitmask specifying the control events for which the
action message is sent.
*/
- (void)addBlockForControlEvents:(UIControlEvents)controlEvents block:(void (^)(id sender))block;
/**
Adds or replaces a block for a particular event (or events) to an internal
dispatch table. It will cause a strong reference to @a block.
@param block The block which is invoked then the action message is
sent (cannot be nil). The block is retained.
@param controlEvents A bitmask specifying the control events for which the
action message is sent.
*/
- (void)setBlockForControlEvents:(UIControlEvents)controlEvents block:(void (^)(id sender))block;
/**
Removes all blocks for a particular event (or events) from an internal
dispatch table.
@param controlEvents A bitmask specifying the control events for which the
action message is sent.
*/
- (void)removeAllBlocksForControlEvents:(UIControlEvents)controlEvents;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIControl+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 527
|
```objective-c
//
// UIScreen+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 13/4/5.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provides extensions for `UIScreen`.
*/
@interface UIScreen (YYAdd)
/**
Main screen's scale
@return screen's scale
*/
+ (CGFloat)screenScale;
/**
Returns the bounds of the screen for the current device orientation.
@return A rect indicating the bounds of the screen.
@see boundsForOrientation:
*/
- (CGRect)currentBounds NS_EXTENSION_UNAVAILABLE_IOS("");
/**
Returns the bounds of the screen for a given device orientation.
`UIScreen`'s `bounds` method always returns the bounds of the
screen of it in the portrait orientation.
@param orientation The orientation to get the screen's bounds.
@return A rect indicating the bounds of the screen.
@see currentBounds
*/
- (CGRect)boundsForOrientation:(UIInterfaceOrientation)orientation;
/**
The screen's real size in pixel (width is always smaller than height).
This value may not be very accurate in an unknown device, or simulator.
e.g. (768,1024)
*/
@property (nonatomic, readonly) CGSize sizeInPixel;
/**
The screen's PPI.
This value may not be very accurate in an unknown device, or simulator.
Default value is 96.
*/
@property (nonatomic, readonly) CGFloat pixelsPerInch;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIScreen+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 338
|
```objective-c
//
// UIDevice+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 13/4/3.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "UIDevice+YYAdd.h"
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <mach/mach.h>
#include <arpa/inet.h>
#include <ifaddrs.h>
#import "YYKitMacro.h"
#import "NSString+YYAdd.h"
YYSYNTH_DUMMY_CLASS(UIDevice_YYAdd)
@implementation UIDevice (YYAdd)
+ (double)systemVersion {
static double version;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
version = [UIDevice currentDevice].systemVersion.doubleValue;
});
return version;
}
- (BOOL)isPad {
static dispatch_once_t one;
static BOOL pad;
dispatch_once(&one, ^{
pad = UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad;
});
return pad;
}
- (BOOL)isSimulator {
#if TARGET_OS_SIMULATOR
return YES;
#else
return NO;
#endif
}
- (BOOL)isJailbroken {
if ([self isSimulator]) return NO; // Dont't check simulator
// iOS9 URL Scheme query changed ...
// NSURL *cydiaURL = [NSURL URLWithString:@"cydia://package"];
// if ([[UIApplication sharedApplication] canOpenURL:cydiaURL]) return YES;
NSArray *paths = @[@"/Applications/Cydia.app",
@"/private/var/lib/apt/",
@"/private/var/lib/cydia",
@"/private/var/stash"];
for (NSString *path in paths) {
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) return YES;
}
FILE *bash = fopen("/bin/bash", "r");
if (bash != NULL) {
fclose(bash);
return YES;
}
NSString *path = [NSString stringWithFormat:@"/private/%@", [NSString stringWithUUID]];
if ([@"test" writeToFile : path atomically : YES encoding : NSUTF8StringEncoding error : NULL]) {
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
return YES;
}
return NO;
}
#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED
- (BOOL)canMakePhoneCalls {
__block BOOL can;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
can = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"tel://"]];
});
return can;
}
#endif
- (NSString *)ipAddressWithIfaName:(NSString *)name {
if (name.length == 0) return nil;
NSString *address = nil;
struct ifaddrs *addrs = NULL;
if (getifaddrs(&addrs) == 0) {
struct ifaddrs *addr = addrs;
while (addr) {
if ([[NSString stringWithUTF8String:addr->ifa_name] isEqualToString:name]) {
sa_family_t family = addr->ifa_addr->sa_family;
switch (family) {
case AF_INET: { // IPv4
char str[INET_ADDRSTRLEN] = {0};
inet_ntop(family, &(((struct sockaddr_in *)addr->ifa_addr)->sin_addr), str, sizeof(str));
if (strlen(str) > 0) {
address = [NSString stringWithUTF8String:str];
}
} break;
case AF_INET6: { // IPv6
char str[INET6_ADDRSTRLEN] = {0};
inet_ntop(family, &(((struct sockaddr_in6 *)addr->ifa_addr)->sin6_addr), str, sizeof(str));
if (strlen(str) > 0) {
address = [NSString stringWithUTF8String:str];
}
}
default: break;
}
if (address) break;
}
addr = addr->ifa_next;
}
}
freeifaddrs(addrs);
return address;
}
- (NSString *)ipAddressWIFI {
return [self ipAddressWithIfaName:@"en0"];
}
- (NSString *)ipAddressCell {
return [self ipAddressWithIfaName:@"pdp_ip0"];
}
typedef struct {
uint64_t en_in;
uint64_t en_out;
uint64_t pdp_ip_in;
uint64_t pdp_ip_out;
uint64_t awdl_in;
uint64_t awdl_out;
} yy_net_interface_counter;
static uint64_t yy_net_counter_add(uint64_t counter, uint64_t bytes) {
if (bytes < (counter % 0xFFFFFFFF)) {
counter += 0xFFFFFFFF - (counter % 0xFFFFFFFF);
counter += bytes;
} else {
counter = bytes;
}
return counter;
}
static uint64_t yy_net_counter_get_by_type(yy_net_interface_counter *counter, YYNetworkTrafficType type) {
uint64_t bytes = 0;
if (type & YYNetworkTrafficTypeWWANSent) bytes += counter->pdp_ip_out;
if (type & YYNetworkTrafficTypeWWANReceived) bytes += counter->pdp_ip_in;
if (type & YYNetworkTrafficTypeWIFISent) bytes += counter->en_out;
if (type & YYNetworkTrafficTypeWIFIReceived) bytes += counter->en_in;
if (type & YYNetworkTrafficTypeAWDLSent) bytes += counter->awdl_out;
if (type & YYNetworkTrafficTypeAWDLReceived) bytes += counter->awdl_in;
return bytes;
}
static yy_net_interface_counter yy_get_net_interface_counter() {
static dispatch_semaphore_t lock;
static NSMutableDictionary *sharedInCounters;
static NSMutableDictionary *sharedOutCounters;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInCounters = [NSMutableDictionary new];
sharedOutCounters = [NSMutableDictionary new];
lock = dispatch_semaphore_create(1);
});
yy_net_interface_counter counter = {0};
struct ifaddrs *addrs;
const struct ifaddrs *cursor;
if (getifaddrs(&addrs) == 0) {
cursor = addrs;
dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
while (cursor) {
if (cursor->ifa_addr->sa_family == AF_LINK) {
const struct if_data *data = cursor->ifa_data;
NSString *name = cursor->ifa_name ? [NSString stringWithUTF8String:cursor->ifa_name] : nil;
if (name) {
uint64_t counter_in = ((NSNumber *)sharedInCounters[name]).unsignedLongLongValue;
counter_in = yy_net_counter_add(counter_in, data->ifi_ibytes);
sharedInCounters[name] = @(counter_in);
uint64_t counter_out = ((NSNumber *)sharedOutCounters[name]).unsignedLongLongValue;
counter_out = yy_net_counter_add(counter_out, data->ifi_obytes);
sharedOutCounters[name] = @(counter_out);
if ([name hasPrefix:@"en"]) {
counter.en_in += counter_in;
counter.en_out += counter_out;
} else if ([name hasPrefix:@"awdl"]) {
counter.awdl_in += counter_in;
counter.awdl_out += counter_out;
} else if ([name hasPrefix:@"pdp_ip"]) {
counter.pdp_ip_in += counter_in;
counter.pdp_ip_out += counter_out;
}
}
}
cursor = cursor->ifa_next;
}
dispatch_semaphore_signal(lock);
freeifaddrs(addrs);
}
return counter;
}
- (uint64_t)getNetworkTrafficBytes:(YYNetworkTrafficType)types {
yy_net_interface_counter counter = yy_get_net_interface_counter();
return yy_net_counter_get_by_type(&counter, types);
}
- (NSString *)machineModel {
static dispatch_once_t one;
static NSString *model;
dispatch_once(&one, ^{
size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char *machine = malloc(size);
sysctlbyname("hw.machine", machine, &size, NULL, 0);
model = [NSString stringWithUTF8String:machine];
free(machine);
});
return model;
}
- (NSString *)machineModelName {
static dispatch_once_t one;
static NSString *name;
dispatch_once(&one, ^{
NSString *model = [self machineModel];
if (!model) return;
NSDictionary *dic = @{
@"Watch1,1" : @"Apple Watch 38mm",
@"Watch1,2" : @"Apple Watch 42mm",
@"Watch2,3" : @"Apple Watch Series 2 38mm",
@"Watch2,4" : @"Apple Watch Series 2 42mm",
@"Watch2,6" : @"Apple Watch Series 1 38mm",
@"Watch1,7" : @"Apple Watch Series 1 42mm",
@"iPod1,1" : @"iPod touch 1",
@"iPod2,1" : @"iPod touch 2",
@"iPod3,1" : @"iPod touch 3",
@"iPod4,1" : @"iPod touch 4",
@"iPod5,1" : @"iPod touch 5",
@"iPod7,1" : @"iPod touch 6",
@"iPhone1,1" : @"iPhone 1G",
@"iPhone1,2" : @"iPhone 3G",
@"iPhone2,1" : @"iPhone 3GS",
@"iPhone3,1" : @"iPhone 4 (GSM)",
@"iPhone3,2" : @"iPhone 4",
@"iPhone3,3" : @"iPhone 4 (CDMA)",
@"iPhone4,1" : @"iPhone 4S",
@"iPhone5,1" : @"iPhone 5",
@"iPhone5,2" : @"iPhone 5",
@"iPhone5,3" : @"iPhone 5c",
@"iPhone5,4" : @"iPhone 5c",
@"iPhone6,1" : @"iPhone 5s",
@"iPhone6,2" : @"iPhone 5s",
@"iPhone7,1" : @"iPhone 6 Plus",
@"iPhone7,2" : @"iPhone 6",
@"iPhone8,1" : @"iPhone 6s",
@"iPhone8,2" : @"iPhone 6s Plus",
@"iPhone8,4" : @"iPhone SE",
@"iPhone9,1" : @"iPhone 7",
@"iPhone9,2" : @"iPhone 7 Plus",
@"iPhone9,3" : @"iPhone 7",
@"iPhone9,4" : @"iPhone 7 Plus",
@"iPad1,1" : @"iPad 1",
@"iPad2,1" : @"iPad 2 (WiFi)",
@"iPad2,2" : @"iPad 2 (GSM)",
@"iPad2,3" : @"iPad 2 (CDMA)",
@"iPad2,4" : @"iPad 2",
@"iPad2,5" : @"iPad mini 1",
@"iPad2,6" : @"iPad mini 1",
@"iPad2,7" : @"iPad mini 1",
@"iPad3,1" : @"iPad 3 (WiFi)",
@"iPad3,2" : @"iPad 3 (4G)",
@"iPad3,3" : @"iPad 3 (4G)",
@"iPad3,4" : @"iPad 4",
@"iPad3,5" : @"iPad 4",
@"iPad3,6" : @"iPad 4",
@"iPad4,1" : @"iPad Air",
@"iPad4,2" : @"iPad Air",
@"iPad4,3" : @"iPad Air",
@"iPad4,4" : @"iPad mini 2",
@"iPad4,5" : @"iPad mini 2",
@"iPad4,6" : @"iPad mini 2",
@"iPad4,7" : @"iPad mini 3",
@"iPad4,8" : @"iPad mini 3",
@"iPad4,9" : @"iPad mini 3",
@"iPad5,1" : @"iPad mini 4",
@"iPad5,2" : @"iPad mini 4",
@"iPad5,3" : @"iPad Air 2",
@"iPad5,4" : @"iPad Air 2",
@"iPad6,3" : @"iPad Pro (9.7 inch)",
@"iPad6,4" : @"iPad Pro (9.7 inch)",
@"iPad6,7" : @"iPad Pro (12.9 inch)",
@"iPad6,8" : @"iPad Pro (12.9 inch)",
@"AppleTV2,1" : @"Apple TV 2",
@"AppleTV3,1" : @"Apple TV 3",
@"AppleTV3,2" : @"Apple TV 3",
@"AppleTV5,3" : @"Apple TV 4",
@"i386" : @"Simulator x86",
@"x86_64" : @"Simulator x64",
};
name = dic[model];
if (!name) name = model;
});
return name;
}
- (NSDate *)systemUptime {
NSTimeInterval time = [[NSProcessInfo processInfo] systemUptime];
return [[NSDate alloc] initWithTimeIntervalSinceNow:(0 - time)];
}
- (int64_t)diskSpace {
NSError *error = nil;
NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
if (error) return -1;
int64_t space = [[attrs objectForKey:NSFileSystemSize] longLongValue];
if (space < 0) space = -1;
return space;
}
- (int64_t)diskSpaceFree {
NSError *error = nil;
NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
if (error) return -1;
int64_t space = [[attrs objectForKey:NSFileSystemFreeSize] longLongValue];
if (space < 0) space = -1;
return space;
}
- (int64_t)diskSpaceUsed {
int64_t total = self.diskSpace;
int64_t free = self.diskSpaceFree;
if (total < 0 || free < 0) return -1;
int64_t used = total - free;
if (used < 0) used = -1;
return used;
}
- (int64_t)memoryTotal {
int64_t mem = [[NSProcessInfo processInfo] physicalMemory];
if (mem < -1) mem = -1;
return mem;
}
- (int64_t)memoryUsed {
mach_port_t host_port = mach_host_self();
mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
vm_size_t page_size;
vm_statistics_data_t vm_stat;
kern_return_t kern;
kern = host_page_size(host_port, &page_size);
if (kern != KERN_SUCCESS) return -1;
kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size);
if (kern != KERN_SUCCESS) return -1;
return page_size * (vm_stat.active_count + vm_stat.inactive_count + vm_stat.wire_count);
}
- (int64_t)memoryFree {
mach_port_t host_port = mach_host_self();
mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
vm_size_t page_size;
vm_statistics_data_t vm_stat;
kern_return_t kern;
kern = host_page_size(host_port, &page_size);
if (kern != KERN_SUCCESS) return -1;
kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size);
if (kern != KERN_SUCCESS) return -1;
return vm_stat.free_count * page_size;
}
- (int64_t)memoryActive {
mach_port_t host_port = mach_host_self();
mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
vm_size_t page_size;
vm_statistics_data_t vm_stat;
kern_return_t kern;
kern = host_page_size(host_port, &page_size);
if (kern != KERN_SUCCESS) return -1;
kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size);
if (kern != KERN_SUCCESS) return -1;
return vm_stat.active_count * page_size;
}
- (int64_t)memoryInactive {
mach_port_t host_port = mach_host_self();
mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
vm_size_t page_size;
vm_statistics_data_t vm_stat;
kern_return_t kern;
kern = host_page_size(host_port, &page_size);
if (kern != KERN_SUCCESS) return -1;
kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size);
if (kern != KERN_SUCCESS) return -1;
return vm_stat.inactive_count * page_size;
}
- (int64_t)memoryWired {
mach_port_t host_port = mach_host_self();
mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
vm_size_t page_size;
vm_statistics_data_t vm_stat;
kern_return_t kern;
kern = host_page_size(host_port, &page_size);
if (kern != KERN_SUCCESS) return -1;
kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size);
if (kern != KERN_SUCCESS) return -1;
return vm_stat.wire_count * page_size;
}
- (int64_t)memoryPurgable {
mach_port_t host_port = mach_host_self();
mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
vm_size_t page_size;
vm_statistics_data_t vm_stat;
kern_return_t kern;
kern = host_page_size(host_port, &page_size);
if (kern != KERN_SUCCESS) return -1;
kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size);
if (kern != KERN_SUCCESS) return -1;
return vm_stat.purgeable_count * page_size;
}
- (NSUInteger)cpuCount {
return [NSProcessInfo processInfo].activeProcessorCount;
}
- (float)cpuUsage {
float cpu = 0;
NSArray *cpus = [self cpuUsagePerProcessor];
if (cpus.count == 0) return -1;
for (NSNumber *n in cpus) {
cpu += n.floatValue;
}
return cpu;
}
- (NSArray *)cpuUsagePerProcessor {
processor_info_array_t _cpuInfo, _prevCPUInfo = nil;
mach_msg_type_number_t _numCPUInfo, _numPrevCPUInfo = 0;
unsigned _numCPUs;
NSLock *_cpuUsageLock;
int _mib[2U] = { CTL_HW, HW_NCPU };
size_t _sizeOfNumCPUs = sizeof(_numCPUs);
int _status = sysctl(_mib, 2U, &_numCPUs, &_sizeOfNumCPUs, NULL, 0U);
if (_status)
_numCPUs = 1;
_cpuUsageLock = [[NSLock alloc] init];
natural_t _numCPUsU = 0U;
kern_return_t err = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &_numCPUsU, &_cpuInfo, &_numCPUInfo);
if (err == KERN_SUCCESS) {
[_cpuUsageLock lock];
NSMutableArray *cpus = [NSMutableArray new];
for (unsigned i = 0U; i < _numCPUs; ++i) {
Float32 _inUse, _total;
if (_prevCPUInfo) {
_inUse = (
(_cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER] - _prevCPUInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER])
+ (_cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM] - _prevCPUInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM])
+ (_cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE] - _prevCPUInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE])
);
_total = _inUse + (_cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE] - _prevCPUInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE]);
} else {
_inUse = _cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER] + _cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM] + _cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE];
_total = _inUse + _cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE];
}
[cpus addObject:@(_inUse / _total)];
}
[_cpuUsageLock unlock];
if (_prevCPUInfo) {
size_t prevCpuInfoSize = sizeof(integer_t) * _numPrevCPUInfo;
vm_deallocate(mach_task_self(), (vm_address_t)_prevCPUInfo, prevCpuInfoSize);
}
return cpus;
} else {
return nil;
}
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIDevice+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 4,810
|
```objective-c
//
// UIDevice+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 13/4/3.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provides extensions for `UIDevice`.
*/
@interface UIDevice (YYAdd)
#pragma mark - Device Information
///=============================================================================
/// @name Device Information
///=============================================================================
/// Device system version (e.g. 8.1)
+ (double)systemVersion;
/// Whether the device is iPad/iPad mini.
@property (nonatomic, readonly) BOOL isPad;
/// Whether the device is a simulator.
@property (nonatomic, readonly) BOOL isSimulator;
/// Whether the device is jailbroken.
@property (nonatomic, readonly) BOOL isJailbroken;
/// Wherher the device can make phone calls.
@property (nonatomic, readonly) BOOL canMakePhoneCalls NS_EXTENSION_UNAVAILABLE_IOS("");
/// The device's machine model. e.g. "iPhone6,1" "iPad4,6"
/// @see path_to_url
@property (nullable, nonatomic, readonly) NSString *machineModel;
/// The device's machine model name. e.g. "iPhone 5s" "iPad mini 2"
/// @see path_to_url
@property (nullable, nonatomic, readonly) NSString *machineModelName;
/// The System's startup time.
@property (nonatomic, readonly) NSDate *systemUptime;
#pragma mark - Network Information
///=============================================================================
/// @name Network Information
///=============================================================================
/// WIFI IP address of this device (can be nil). e.g. @"192.168.1.111"
@property (nullable, nonatomic, readonly) NSString *ipAddressWIFI;
/// Cell IP address of this device (can be nil). e.g. @"10.2.2.222"
@property (nullable, nonatomic, readonly) NSString *ipAddressCell;
/**
Network traffic type:
WWAN: Wireless Wide Area Network.
For example: 3G/4G.
WIFI: Wi-Fi.
AWDL: Apple Wireless Direct Link (peer-to-peer connection).
For exmaple: AirDrop, AirPlay, GameKit.
*/
typedef NS_OPTIONS(NSUInteger, YYNetworkTrafficType) {
YYNetworkTrafficTypeWWANSent = 1 << 0,
YYNetworkTrafficTypeWWANReceived = 1 << 1,
YYNetworkTrafficTypeWIFISent = 1 << 2,
YYNetworkTrafficTypeWIFIReceived = 1 << 3,
YYNetworkTrafficTypeAWDLSent = 1 << 4,
YYNetworkTrafficTypeAWDLReceived = 1 << 5,
YYNetworkTrafficTypeWWAN = YYNetworkTrafficTypeWWANSent | YYNetworkTrafficTypeWWANReceived,
YYNetworkTrafficTypeWIFI = YYNetworkTrafficTypeWIFISent | YYNetworkTrafficTypeWIFIReceived,
YYNetworkTrafficTypeAWDL = YYNetworkTrafficTypeAWDLSent | YYNetworkTrafficTypeAWDLReceived,
YYNetworkTrafficTypeALL = YYNetworkTrafficTypeWWAN |
YYNetworkTrafficTypeWIFI |
YYNetworkTrafficTypeAWDL,
};
/**
Get device network traffic bytes.
@discussion This is a counter since the device's last boot time.
Usage:
uint64_t bytes = [[UIDevice currentDevice] getNetworkTrafficBytes:YYNetworkTrafficTypeALL];
NSTimeInterval time = CACurrentMediaTime();
uint64_t bytesPerSecond = (bytes - _lastBytes) / (time - _lastTime);
_lastBytes = bytes;
_lastTime = time;
@param type traffic types
@return bytes counter.
*/
- (uint64_t)getNetworkTrafficBytes:(YYNetworkTrafficType)types;
#pragma mark - Disk Space
///=============================================================================
/// @name Disk Space
///=============================================================================
/// Total disk space in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t diskSpace;
/// Free disk space in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t diskSpaceFree;
/// Used disk space in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t diskSpaceUsed;
#pragma mark - Memory Information
///=============================================================================
/// @name Memory Information
///=============================================================================
/// Total physical memory in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t memoryTotal;
/// Used (active + inactive + wired) memory in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t memoryUsed;
/// Free memory in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t memoryFree;
/// Acvite memory in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t memoryActive;
/// Inactive memory in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t memoryInactive;
/// Wired memory in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t memoryWired;
/// Purgable memory in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t memoryPurgable;
#pragma mark - CPU Information
///=============================================================================
/// @name CPU Information
///=============================================================================
/// Avaliable CPU processor count.
@property (nonatomic, readonly) NSUInteger cpuCount;
/// Current CPU usage, 1.0 means 100%. (-1 when error occurs)
@property (nonatomic, readonly) float cpuUsage;
/// Current CPU usage per processor (array of NSNumber), 1.0 means 100%. (nil when error occurs)
@property (nullable, nonatomic, readonly) NSArray<NSNumber *> *cpuUsagePerProcessor;
@end
NS_ASSUME_NONNULL_END
#ifndef kSystemVersion
#define kSystemVersion [UIDevice systemVersion]
#endif
#ifndef kiOS6Later
#define kiOS6Later (kSystemVersion >= 6)
#endif
#ifndef kiOS7Later
#define kiOS7Later (kSystemVersion >= 7)
#endif
#ifndef kiOS8Later
#define kiOS8Later (kSystemVersion >= 8)
#endif
#ifndef kiOS9Later
#define kiOS9Later (kSystemVersion >= 9)
#endif
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIDevice+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,340
|
```objective-c
//
// UIImage+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 13/4/4.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "UIImage+YYAdd.h"
#import "UIDevice+YYAdd.h"
#import "NSString+YYAdd.h"
#import "YYKitMacro.h"
#import "YYCGUtilities.h"
#import <ImageIO/ImageIO.h>
#import <Accelerate/Accelerate.h>
#import <CoreText/CoreText.h>
#import <objc/runtime.h>
#import "YYCGUtilities.h"
YYSYNTH_DUMMY_CLASS(UIImage_YYAdd)
static NSTimeInterval _yy_CGImageSourceGetGIFFrameDelayAtIndex(CGImageSourceRef source, size_t index) {
NSTimeInterval delay = 0;
CFDictionaryRef dic = CGImageSourceCopyPropertiesAtIndex(source, index, NULL);
if (dic) {
CFDictionaryRef dicGIF = CFDictionaryGetValue(dic, kCGImagePropertyGIFDictionary);
if (dicGIF) {
NSNumber *num = CFDictionaryGetValue(dicGIF, kCGImagePropertyGIFUnclampedDelayTime);
if (num.doubleValue <= __FLT_EPSILON__) {
num = CFDictionaryGetValue(dicGIF, kCGImagePropertyGIFDelayTime);
}
delay = num.doubleValue;
}
CFRelease(dic);
}
// path_to_url
if (delay < 0.02) delay = 0.1;
return delay;
}
@implementation UIImage (YYAdd)
+ (UIImage *)imageWithSmallGIFData:(NSData *)data scale:(CGFloat)scale {
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFTypeRef)(data), NULL);
if (!source) return nil;
size_t count = CGImageSourceGetCount(source);
if (count <= 1) {
CFRelease(source);
return [self.class imageWithData:data scale:scale];
}
NSUInteger frames[count];
double oneFrameTime = 1 / 50.0; // 50 fps
NSTimeInterval totalTime = 0;
NSUInteger totalFrame = 0;
NSUInteger gcdFrame = 0;
for (size_t i = 0; i < count; i++) {
NSTimeInterval delay = _yy_CGImageSourceGetGIFFrameDelayAtIndex(source, i);
totalTime += delay;
NSInteger frame = lrint(delay / oneFrameTime);
if (frame < 1) frame = 1;
frames[i] = frame;
totalFrame += frames[i];
if (i == 0) gcdFrame = frames[i];
else {
NSUInteger frame = frames[i], tmp;
if (frame < gcdFrame) {
tmp = frame; frame = gcdFrame; gcdFrame = tmp;
}
while (true) {
tmp = frame % gcdFrame;
if (tmp == 0) break;
frame = gcdFrame;
gcdFrame = tmp;
}
}
}
NSMutableArray *array = [NSMutableArray new];
for (size_t i = 0; i < count; i++) {
CGImageRef imageRef = CGImageSourceCreateImageAtIndex(source, i, NULL);
if (!imageRef) {
CFRelease(source);
return nil;
}
size_t width = CGImageGetWidth(imageRef);
size_t height = CGImageGetHeight(imageRef);
if (width == 0 || height == 0) {
CFRelease(source);
CFRelease(imageRef);
return nil;
}
CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef) & kCGBitmapAlphaInfoMask;
BOOL hasAlpha = NO;
if (alphaInfo == kCGImageAlphaPremultipliedLast ||
alphaInfo == kCGImageAlphaPremultipliedFirst ||
alphaInfo == kCGImageAlphaLast ||
alphaInfo == kCGImageAlphaFirst) {
hasAlpha = YES;
}
// BGRA8888 (premultiplied) or BGRX8888
// same as UIGraphicsBeginImageContext() and -[UIView drawRect:]
CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Host;
bitmapInfo |= hasAlpha ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaNoneSkipFirst;
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, space, bitmapInfo);
CGColorSpaceRelease(space);
if (!context) {
CFRelease(source);
CFRelease(imageRef);
return nil;
}
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); // decode
CGImageRef decoded = CGBitmapContextCreateImage(context);
CFRelease(context);
if (!decoded) {
CFRelease(source);
CFRelease(imageRef);
return nil;
}
UIImage *image = [UIImage imageWithCGImage:decoded scale:scale orientation:UIImageOrientationUp];
CGImageRelease(imageRef);
CGImageRelease(decoded);
if (!image) {
CFRelease(source);
return nil;
}
for (size_t j = 0, max = frames[i] / gcdFrame; j < max; j++) {
[array addObject:image];
}
}
CFRelease(source);
UIImage *image = [self.class animatedImageWithImages:array duration:totalTime];
return image;
}
+ (BOOL)isAnimatedGIFData:(NSData *)data {
if (data.length < 16) return NO;
UInt32 magic = *(UInt32 *)data.bytes;
// path_to_url
if ((magic & 0xFFFFFF) != '\0FIG') return NO;
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFTypeRef)data, NULL);
if (!source) return NO;
size_t count = CGImageSourceGetCount(source);
CFRelease(source);
return count > 1;
}
+ (BOOL)isAnimatedGIFFile:(NSString *)path {
if (path.length == 0) return NO;
const char *cpath = path.UTF8String;
FILE *fd = fopen(cpath, "rb");
if (!fd) return NO;
BOOL isGIF = NO;
UInt32 magic = 0;
if (fread(&magic, sizeof(UInt32), 1, fd) == 1) {
if ((magic & 0xFFFFFF) == '\0FIG') isGIF = YES;
}
fclose(fd);
return isGIF;
}
+ (UIImage *)imageWithPDF:(id)dataOrPath {
return [self _yy_imageWithPDF:dataOrPath resize:NO size:CGSizeZero];
}
+ (UIImage *)imageWithPDF:(id)dataOrPath size:(CGSize)size {
return [self _yy_imageWithPDF:dataOrPath resize:YES size:size];
}
+ (UIImage *)imageWithEmoji:(NSString *)emoji size:(CGFloat)size {
if (emoji.length == 0) return nil;
if (size < 1) return nil;
CGFloat scale = [UIScreen mainScreen].scale;
CTFontRef font = CTFontCreateWithName(CFSTR("AppleColorEmoji"), size * scale, NULL);
if (!font) return nil;
NSAttributedString *str = [[NSAttributedString alloc] initWithString:emoji attributes:@{ (__bridge id)kCTFontAttributeName:(__bridge id)font, (__bridge id)kCTForegroundColorAttributeName:(__bridge id)[UIColor whiteColor].CGColor }];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef ctx = CGBitmapContextCreate(NULL, size * scale, size * scale, 8, 0, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh);
CTLineRef line = CTLineCreateWithAttributedString((__bridge CFTypeRef)str);
CGRect bounds = CTLineGetBoundsWithOptions(line, kCTLineBoundsUseGlyphPathBounds);
CGContextSetTextPosition(ctx, 0, -bounds.origin.y);
CTLineDraw(line, ctx);
CGImageRef imageRef = CGBitmapContextCreateImage(ctx);
UIImage *image = [[UIImage alloc] initWithCGImage:imageRef scale:scale orientation:UIImageOrientationUp];
CFRelease(font);
CGColorSpaceRelease(colorSpace);
CGContextRelease(ctx);
if (line)CFRelease(line);
if (imageRef) CFRelease(imageRef);
return image;
}
+ (UIImage *)_yy_imageWithPDF:(id)dataOrPath resize:(BOOL)resize size:(CGSize)size {
CGPDFDocumentRef pdf = NULL;
if ([dataOrPath isKindOfClass:[NSData class]]) {
CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)dataOrPath);
pdf = CGPDFDocumentCreateWithProvider(provider);
CGDataProviderRelease(provider);
} else if ([dataOrPath isKindOfClass:[NSString class]]) {
pdf = CGPDFDocumentCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:dataOrPath]);
}
if (!pdf) return nil;
CGPDFPageRef page = CGPDFDocumentGetPage(pdf, 1);
if (!page) {
CGPDFDocumentRelease(pdf);
return nil;
}
CGRect pdfRect = CGPDFPageGetBoxRect(page, kCGPDFCropBox);
CGSize pdfSize = resize ? size : pdfRect.size;
CGFloat scale = [UIScreen mainScreen].scale;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef ctx = CGBitmapContextCreate(NULL, pdfSize.width * scale, pdfSize.height * scale, 8, 0, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
if (!ctx) {
CGColorSpaceRelease(colorSpace);
CGPDFDocumentRelease(pdf);
return nil;
}
CGContextScaleCTM(ctx, scale, scale);
CGContextTranslateCTM(ctx, -pdfRect.origin.x, -pdfRect.origin.y);
CGContextDrawPDFPage(ctx, page);
CGPDFDocumentRelease(pdf);
CGImageRef image = CGBitmapContextCreateImage(ctx);
UIImage *pdfImage = [[UIImage alloc] initWithCGImage:image scale:scale orientation:UIImageOrientationUp];
CGImageRelease(image);
CGContextRelease(ctx);
CGColorSpaceRelease(colorSpace);
return pdfImage;
}
+ (UIImage *)imageWithColor:(UIColor *)color {
return [self imageWithColor:color size:CGSizeMake(1, 1)];
}
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
if (!color || size.width <= 0 || size.height <= 0) return nil;
CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
+ (UIImage *)imageWithSize:(CGSize)size drawBlock:(void (^)(CGContextRef context))drawBlock {
if (!drawBlock) return nil;
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
if (!context) return nil;
drawBlock(context);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
- (BOOL)hasAlphaChannel {
if (self.CGImage == NULL) return NO;
CGImageAlphaInfo alpha = CGImageGetAlphaInfo(self.CGImage) & kCGBitmapAlphaInfoMask;
return (alpha == kCGImageAlphaFirst ||
alpha == kCGImageAlphaLast ||
alpha == kCGImageAlphaPremultipliedFirst ||
alpha == kCGImageAlphaPremultipliedLast);
}
- (void)drawInRect:(CGRect)rect withContentMode:(UIViewContentMode)contentMode clipsToBounds:(BOOL)clips{
CGRect drawRect = YYCGRectFitWithContentMode(rect, self.size, contentMode);
if (drawRect.size.width == 0 || drawRect.size.height == 0) return;
if (clips) {
CGContextRef context = UIGraphicsGetCurrentContext();
if (context) {
CGContextSaveGState(context);
CGContextAddRect(context, rect);
CGContextClip(context);
[self drawInRect:drawRect];
CGContextRestoreGState(context);
}
} else {
[self drawInRect:drawRect];
}
}
- (UIImage *)imageByResizeToSize:(CGSize)size {
if (size.width <= 0 || size.height <= 0) return nil;
UIGraphicsBeginImageContextWithOptions(size, NO, self.scale);
[self drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
- (UIImage *)imageByResizeToSize:(CGSize)size contentMode:(UIViewContentMode)contentMode {
if (size.width <= 0 || size.height <= 0) return nil;
UIGraphicsBeginImageContextWithOptions(size, NO, self.scale);
[self drawInRect:CGRectMake(0, 0, size.width, size.height) withContentMode:contentMode clipsToBounds:NO];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
- (UIImage *)imageByCropToRect:(CGRect)rect {
rect.origin.x *= self.scale;
rect.origin.y *= self.scale;
rect.size.width *= self.scale;
rect.size.height *= self.scale;
if (rect.size.width <= 0 || rect.size.height <= 0) return nil;
CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
UIImage *image = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
CGImageRelease(imageRef);
return image;
}
- (UIImage *)imageByInsetEdge:(UIEdgeInsets)insets withColor:(UIColor *)color {
CGSize size = self.size;
size.width -= insets.left + insets.right;
size.height -= insets.top + insets.bottom;
if (size.width <= 0 || size.height <= 0) return nil;
CGRect rect = CGRectMake(-insets.left, -insets.top, self.size.width, self.size.height);
UIGraphicsBeginImageContextWithOptions(size, NO, self.scale);
CGContextRef context = UIGraphicsGetCurrentContext();
if (color) {
CGContextSetFillColorWithColor(context, color.CGColor);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(0, 0, size.width, size.height));
CGPathAddRect(path, NULL, rect);
CGContextAddPath(context, path);
CGContextEOFillPath(context);
CGPathRelease(path);
}
[self drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
- (UIImage *)imageByRoundCornerRadius:(CGFloat)radius {
return [self imageByRoundCornerRadius:radius borderWidth:0 borderColor:nil];
}
- (UIImage *)imageByRoundCornerRadius:(CGFloat)radius
borderWidth:(CGFloat)borderWidth
borderColor:(UIColor *)borderColor {
return [self imageByRoundCornerRadius:radius
corners:UIRectCornerAllCorners
borderWidth:borderWidth
borderColor:borderColor
borderLineJoin:kCGLineJoinMiter];
}
- (UIImage *)imageByRoundCornerRadius:(CGFloat)radius
corners:(UIRectCorner)corners
borderWidth:(CGFloat)borderWidth
borderColor:(UIColor *)borderColor
borderLineJoin:(CGLineJoin)borderLineJoin {
if (corners != UIRectCornerAllCorners) {
UIRectCorner tmp = 0;
if (corners & UIRectCornerTopLeft) tmp |= UIRectCornerBottomLeft;
if (corners & UIRectCornerTopRight) tmp |= UIRectCornerBottomRight;
if (corners & UIRectCornerBottomLeft) tmp |= UIRectCornerTopLeft;
if (corners & UIRectCornerBottomRight) tmp |= UIRectCornerTopRight;
corners = tmp;
}
UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextScaleCTM(context, 1, -1);
CGContextTranslateCTM(context, 0, -rect.size.height);
CGFloat minSize = MIN(self.size.width, self.size.height);
if (borderWidth < minSize / 2) {
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectInset(rect, borderWidth, borderWidth) byRoundingCorners:corners cornerRadii:CGSizeMake(radius, borderWidth)];
[path closePath];
CGContextSaveGState(context);
[path addClip];
CGContextDrawImage(context, rect, self.CGImage);
CGContextRestoreGState(context);
}
if (borderColor && borderWidth < minSize / 2 && borderWidth > 0) {
CGFloat strokeInset = (floor(borderWidth * self.scale) + 0.5) / self.scale;
CGRect strokeRect = CGRectInset(rect, strokeInset, strokeInset);
CGFloat strokeRadius = radius > self.scale / 2 ? radius - self.scale / 2 : 0;
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:strokeRect byRoundingCorners:corners cornerRadii:CGSizeMake(strokeRadius, borderWidth)];
[path closePath];
path.lineWidth = borderWidth;
path.lineJoinStyle = borderLineJoin;
[borderColor setStroke];
[path stroke];
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
- (UIImage *)imageByRotate:(CGFloat)radians fitSize:(BOOL)fitSize {
size_t width = (size_t)CGImageGetWidth(self.CGImage);
size_t height = (size_t)CGImageGetHeight(self.CGImage);
CGRect newRect = CGRectApplyAffineTransform(CGRectMake(0., 0., width, height),
fitSize ? CGAffineTransformMakeRotation(radians) : CGAffineTransformIdentity);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL,
(size_t)newRect.size.width,
(size_t)newRect.size.height,
8,
(size_t)newRect.size.width * 4,
colorSpace,
kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace);
if (!context) return nil;
CGContextSetShouldAntialias(context, true);
CGContextSetAllowsAntialiasing(context, true);
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGContextTranslateCTM(context, +(newRect.size.width * 0.5), +(newRect.size.height * 0.5));
CGContextRotateCTM(context, radians);
CGContextDrawImage(context, CGRectMake(-(width * 0.5), -(height * 0.5), width, height), self.CGImage);
CGImageRef imgRef = CGBitmapContextCreateImage(context);
UIImage *img = [UIImage imageWithCGImage:imgRef scale:self.scale orientation:self.imageOrientation];
CGImageRelease(imgRef);
CGContextRelease(context);
return img;
}
- (UIImage *)_yy_flipHorizontal:(BOOL)horizontal vertical:(BOOL)vertical {
if (!self.CGImage) return nil;
size_t width = (size_t)CGImageGetWidth(self.CGImage);
size_t height = (size_t)CGImageGetHeight(self.CGImage);
size_t bytesPerRow = width * 4;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace);
if (!context) return nil;
CGContextDrawImage(context, CGRectMake(0, 0, width, height), self.CGImage);
UInt8 *data = (UInt8 *)CGBitmapContextGetData(context);
if (!data) {
CGContextRelease(context);
return nil;
}
vImage_Buffer src = { data, height, width, bytesPerRow };
vImage_Buffer dest = { data, height, width, bytesPerRow };
if (vertical) {
vImageVerticalReflect_ARGB8888(&src, &dest, kvImageBackgroundColorFill);
}
if (horizontal) {
vImageHorizontalReflect_ARGB8888(&src, &dest, kvImageBackgroundColorFill);
}
CGImageRef imgRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
UIImage *img = [UIImage imageWithCGImage:imgRef scale:self.scale orientation:self.imageOrientation];
CGImageRelease(imgRef);
return img;
}
- (UIImage *)imageByRotateLeft90 {
return [self imageByRotate:DegreesToRadians(90) fitSize:YES];
}
- (UIImage *)imageByRotateRight90 {
return [self imageByRotate:DegreesToRadians(-90) fitSize:YES];
}
- (UIImage *)imageByRotate180 {
return [self _yy_flipHorizontal:YES vertical:YES];
}
- (UIImage *)imageByFlipVertical {
return [self _yy_flipHorizontal:NO vertical:YES];
}
- (UIImage *)imageByFlipHorizontal {
return [self _yy_flipHorizontal:YES vertical:NO];
}
- (UIImage *)imageByTintColor:(UIColor *)color {
UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
[color set];
UIRectFill(rect);
[self drawAtPoint:CGPointMake(0, 0) blendMode:kCGBlendModeDestinationIn alpha:1];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
- (UIImage *)imageByGrayscale {
return [self imageByBlurRadius:0 tintColor:nil tintMode:0 saturation:0 maskImage:nil];
}
- (UIImage *)imageByBlurSoft {
return [self imageByBlurRadius:60 tintColor:[UIColor colorWithWhite:0.84 alpha:0.36] tintMode:kCGBlendModeNormal saturation:1.8 maskImage:nil];
}
- (UIImage *)imageByBlurLight {
return [self imageByBlurRadius:60 tintColor:[UIColor colorWithWhite:1.0 alpha:0.3] tintMode:kCGBlendModeNormal saturation:1.8 maskImage:nil];
}
- (UIImage *)imageByBlurExtraLight {
return [self imageByBlurRadius:40 tintColor:[UIColor colorWithWhite:0.97 alpha:0.82] tintMode:kCGBlendModeNormal saturation:1.8 maskImage:nil];
}
- (UIImage *)imageByBlurDark {
return [self imageByBlurRadius:40 tintColor:[UIColor colorWithWhite:0.11 alpha:0.73] tintMode:kCGBlendModeNormal saturation:1.8 maskImage:nil];
}
- (UIImage *)imageByBlurWithTint:(UIColor *)tintColor {
const CGFloat EffectColorAlpha = 0.6;
UIColor *effectColor = tintColor;
size_t componentCount = CGColorGetNumberOfComponents(tintColor.CGColor);
if (componentCount == 2) {
CGFloat b;
if ([tintColor getWhite:&b alpha:NULL]) {
effectColor = [UIColor colorWithWhite:b alpha:EffectColorAlpha];
}
} else {
CGFloat r, g, b;
if ([tintColor getRed:&r green:&g blue:&b alpha:NULL]) {
effectColor = [UIColor colorWithRed:r green:g blue:b alpha:EffectColorAlpha];
}
}
return [self imageByBlurRadius:20 tintColor:effectColor tintMode:kCGBlendModeNormal saturation:-1.0 maskImage:nil];
}
- (UIImage *)imageByBlurRadius:(CGFloat)blurRadius
tintColor:(UIColor *)tintColor
tintMode:(CGBlendMode)tintBlendMode
saturation:(CGFloat)saturation
maskImage:(UIImage *)maskImage {
if (self.size.width < 1 || self.size.height < 1) {
NSLog(@"UIImage+YYAdd error: invalid size: (%.2f x %.2f). Both dimensions must be >= 1: %@", self.size.width, self.size.height, self);
return nil;
}
if (!self.CGImage) {
NSLog(@"UIImage+YYAdd error: inputImage must be backed by a CGImage: %@", self);
return nil;
}
if (maskImage && !maskImage.CGImage) {
NSLog(@"UIImage+YYAdd error: effectMaskImage must be backed by a CGImage: %@", maskImage);
return nil;
}
// iOS7 and above can use new func.
BOOL hasNewFunc = (long)vImageBuffer_InitWithCGImage != 0 && (long)vImageCreateCGImageFromBuffer != 0;
BOOL hasBlur = blurRadius > __FLT_EPSILON__;
BOOL hasSaturation = fabs(saturation - 1.0) > __FLT_EPSILON__;
CGSize size = self.size;
CGRect rect = { CGPointZero, size };
CGFloat scale = self.scale;
CGImageRef imageRef = self.CGImage;
BOOL opaque = NO;
if (!hasBlur && !hasSaturation) {
return [self _yy_mergeImageRef:imageRef tintColor:tintColor tintBlendMode:tintBlendMode maskImage:maskImage opaque:opaque];
}
vImage_Buffer effect = { 0 }, scratch = { 0 };
vImage_Buffer *input = NULL, *output = NULL;
vImage_CGImageFormat format = {
.bitsPerComponent = 8,
.bitsPerPixel = 32,
.colorSpace = NULL,
.bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little, //requests a BGRA buffer.
.version = 0,
.decode = NULL,
.renderingIntent = kCGRenderingIntentDefault
};
if (hasNewFunc) {
vImage_Error err;
err = vImageBuffer_InitWithCGImage(&effect, &format, NULL, imageRef, kvImagePrintDiagnosticsToConsole);
if (err != kvImageNoError) {
NSLog(@"UIImage+YYAdd error: vImageBuffer_InitWithCGImage returned error code %zi for inputImage: %@", err, self);
return nil;
}
err = vImageBuffer_Init(&scratch, effect.height, effect.width, format.bitsPerPixel, kvImageNoFlags);
if (err != kvImageNoError) {
NSLog(@"UIImage+YYAdd error: vImageBuffer_Init returned error code %zi for inputImage: %@", err, self);
return nil;
}
} else {
UIGraphicsBeginImageContextWithOptions(size, opaque, scale);
CGContextRef effectCtx = UIGraphicsGetCurrentContext();
CGContextScaleCTM(effectCtx, 1.0, -1.0);
CGContextTranslateCTM(effectCtx, 0, -size.height);
CGContextDrawImage(effectCtx, rect, imageRef);
effect.data = CGBitmapContextGetData(effectCtx);
effect.width = CGBitmapContextGetWidth(effectCtx);
effect.height = CGBitmapContextGetHeight(effectCtx);
effect.rowBytes = CGBitmapContextGetBytesPerRow(effectCtx);
UIGraphicsBeginImageContextWithOptions(size, opaque, scale);
CGContextRef scratchCtx = UIGraphicsGetCurrentContext();
scratch.data = CGBitmapContextGetData(scratchCtx);
scratch.width = CGBitmapContextGetWidth(scratchCtx);
scratch.height = CGBitmapContextGetHeight(scratchCtx);
scratch.rowBytes = CGBitmapContextGetBytesPerRow(scratchCtx);
}
input = &effect;
output = &scratch;
if (hasBlur) {
// A description of how to compute the box kernel width from the Gaussian
// radius (aka standard deviation) appears in the SVG spec:
// path_to_url#feGaussianBlurElement
//
// For larger values of 's' (s >= 2.0), an approximation can be used: Three
// successive box-blurs build a piece-wise quadratic convolution kernel, which
// approximates the Gaussian kernel to within roughly 3%.
//
// let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
//
// ... if d is odd, use three box-blurs of size 'd', centered on the output pixel.
//
CGFloat inputRadius = blurRadius * scale;
if (inputRadius - 2.0 < __FLT_EPSILON__) inputRadius = 2.0;
uint32_t radius = floor((inputRadius * 3.0 * sqrt(2 * M_PI) / 4 + 0.5) / 2);
radius |= 1; // force radius to be odd so that the three box-blur methodology works.
int iterations;
if (blurRadius * scale < 0.5) iterations = 1;
else if (blurRadius * scale < 1.5) iterations = 2;
else iterations = 3;
NSInteger tempSize = vImageBoxConvolve_ARGB8888(input, output, NULL, 0, 0, radius, radius, NULL, kvImageGetTempBufferSize | kvImageEdgeExtend);
void *temp = malloc(tempSize);
for (int i = 0; i < iterations; i++) {
vImageBoxConvolve_ARGB8888(input, output, temp, 0, 0, radius, radius, NULL, kvImageEdgeExtend);
YY_SWAP(input, output);
}
free(temp);
}
if (hasSaturation) {
// These values appear in the W3C Filter Effects spec:
// path_to_url#grayscaleEquivalent
CGFloat s = saturation;
CGFloat matrixFloat[] = {
0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0,
0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0,
0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0,
0, 0, 0, 1,
};
const int32_t divisor = 256;
NSUInteger matrixSize = sizeof(matrixFloat) / sizeof(matrixFloat[0]);
int16_t matrix[matrixSize];
for (NSUInteger i = 0; i < matrixSize; ++i) {
matrix[i] = (int16_t)roundf(matrixFloat[i] * divisor);
}
vImageMatrixMultiply_ARGB8888(input, output, matrix, divisor, NULL, NULL, kvImageNoFlags);
YY_SWAP(input, output);
}
UIImage *outputImage = nil;
if (hasNewFunc) {
CGImageRef effectCGImage = NULL;
effectCGImage = vImageCreateCGImageFromBuffer(input, &format, &_yy_cleanupBuffer, NULL, kvImageNoAllocate, NULL);
if (effectCGImage == NULL) {
effectCGImage = vImageCreateCGImageFromBuffer(input, &format, NULL, NULL, kvImageNoFlags, NULL);
free(input->data);
}
free(output->data);
outputImage = [self _yy_mergeImageRef:effectCGImage tintColor:tintColor tintBlendMode:tintBlendMode maskImage:maskImage opaque:opaque];
CGImageRelease(effectCGImage);
} else {
CGImageRef effectCGImage;
UIImage *effectImage;
if (input != &effect) effectImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if (input == &effect) effectImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
effectCGImage = effectImage.CGImage;
outputImage = [self _yy_mergeImageRef:effectCGImage tintColor:tintColor tintBlendMode:tintBlendMode maskImage:maskImage opaque:opaque];
}
return outputImage;
}
// Helper function to handle deferred cleanup of a buffer.
static void _yy_cleanupBuffer(void *userData, void *buf_data) {
free(buf_data);
}
// Helper function to add tint and mask.
- (UIImage *)_yy_mergeImageRef:(CGImageRef)effectCGImage
tintColor:(UIColor *)tintColor
tintBlendMode:(CGBlendMode)tintBlendMode
maskImage:(UIImage *)maskImage
opaque:(BOOL)opaque {
BOOL hasTint = tintColor != nil && CGColorGetAlpha(tintColor.CGColor) > __FLT_EPSILON__;
BOOL hasMask = maskImage != nil;
CGSize size = self.size;
CGRect rect = { CGPointZero, size };
CGFloat scale = self.scale;
if (!hasTint && !hasMask) {
return [UIImage imageWithCGImage:effectCGImage];
}
UIGraphicsBeginImageContextWithOptions(size, opaque, scale);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextScaleCTM(context, 1.0, -1.0);
CGContextTranslateCTM(context, 0, -size.height);
if (hasMask) {
CGContextDrawImage(context, rect, self.CGImage);
CGContextSaveGState(context);
CGContextClipToMask(context, rect, maskImage.CGImage);
}
CGContextDrawImage(context, rect, effectCGImage);
if (hasTint) {
CGContextSaveGState(context);
CGContextSetBlendMode(context, tintBlendMode);
CGContextSetFillColorWithColor(context, tintColor.CGColor);
CGContextFillRect(context, rect);
CGContextRestoreGState(context);
}
if (hasMask) {
CGContextRestoreGState(context);
}
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return outputImage;
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIImage+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 7,550
|
```objective-c
//
// UIControl+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 13/4/5.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "UIControl+YYAdd.h"
#import "YYKitMacro.h"
#import <objc/runtime.h>
YYSYNTH_DUMMY_CLASS(UIControl_YYAdd)
static const int block_key;
@interface _YYUIControlBlockTarget : NSObject
@property (nonatomic, copy) void (^block)(id sender);
@property (nonatomic, assign) UIControlEvents events;
- (id)initWithBlock:(void (^)(id sender))block events:(UIControlEvents)events;
- (void)invoke:(id)sender;
@end
@implementation _YYUIControlBlockTarget
- (id)initWithBlock:(void (^)(id sender))block events:(UIControlEvents)events {
self = [super init];
if (self) {
_block = [block copy];
_events = events;
}
return self;
}
- (void)invoke:(id)sender {
if (_block) _block(sender);
}
@end
@implementation UIControl (YYAdd)
- (void)removeAllTargets {
[[self allTargets] enumerateObjectsUsingBlock: ^(id object, BOOL *stop) {
[self removeTarget:object action:NULL forControlEvents:UIControlEventAllEvents];
}];
[[self _yy_allUIControlBlockTargets] removeAllObjects];
}
- (void)setTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents {
if (!target || !action || !controlEvents) return;
NSSet *targets = [self allTargets];
for (id currentTarget in targets) {
NSArray *actions = [self actionsForTarget:currentTarget forControlEvent:controlEvents];
for (NSString *currentAction in actions) {
[self removeTarget:currentTarget action:NSSelectorFromString(currentAction)
forControlEvents:controlEvents];
}
}
[self addTarget:target action:action forControlEvents:controlEvents];
}
- (void)addBlockForControlEvents:(UIControlEvents)controlEvents
block:(void (^)(id sender))block {
if (!controlEvents) return;
_YYUIControlBlockTarget *target = [[_YYUIControlBlockTarget alloc]
initWithBlock:block events:controlEvents];
[self addTarget:target action:@selector(invoke:) forControlEvents:controlEvents];
NSMutableArray *targets = [self _yy_allUIControlBlockTargets];
[targets addObject:target];
}
- (void)setBlockForControlEvents:(UIControlEvents)controlEvents
block:(void (^)(id sender))block {
[self removeAllBlocksForControlEvents:UIControlEventAllEvents];
[self addBlockForControlEvents:controlEvents block:block];
}
- (void)removeAllBlocksForControlEvents:(UIControlEvents)controlEvents {
if (!controlEvents) return;
NSMutableArray *targets = [self _yy_allUIControlBlockTargets];
NSMutableArray *removes = [NSMutableArray array];
for (_YYUIControlBlockTarget *target in targets) {
if (target.events & controlEvents) {
UIControlEvents newEvent = target.events & (~controlEvents);
if (newEvent) {
[self removeTarget:target action:@selector(invoke:) forControlEvents:target.events];
target.events = newEvent;
[self addTarget:target action:@selector(invoke:) forControlEvents:target.events];
} else {
[self removeTarget:target action:@selector(invoke:) forControlEvents:target.events];
[removes addObject:target];
}
}
}
[targets removeObjectsInArray:removes];
}
- (NSMutableArray *)_yy_allUIControlBlockTargets {
NSMutableArray *targets = objc_getAssociatedObject(self, &block_key);
if (!targets) {
targets = [NSMutableArray array];
objc_setAssociatedObject(self, &block_key, targets, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return targets;
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIControl+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 855
|
```objective-c
//
// UIBarButtonItem+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 13/10/15.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "UIBarButtonItem+YYAdd.h"
#import "YYKitMacro.h"
#import <objc/runtime.h>
YYSYNTH_DUMMY_CLASS(UIBarButtonItem_YYAdd)
static const int block_key;
@interface _YYUIBarButtonItemBlockTarget : NSObject
@property (nonatomic, copy) void (^block)(id sender);
- (id)initWithBlock:(void (^)(id sender))block;
- (void)invoke:(id)sender;
@end
@implementation _YYUIBarButtonItemBlockTarget
- (id)initWithBlock:(void (^)(id sender))block{
self = [super init];
if (self) {
_block = [block copy];
}
return self;
}
- (void)invoke:(id)sender {
if (self.block) self.block(sender);
}
@end
@implementation UIBarButtonItem (YYAdd)
- (void)setActionBlock:(void (^)(id sender))block {
_YYUIBarButtonItemBlockTarget *target = [[_YYUIBarButtonItemBlockTarget alloc] initWithBlock:block];
objc_setAssociatedObject(self, &block_key, target, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self setTarget:target];
[self setAction:@selector(invoke:)];
}
- (void (^)(id)) actionBlock {
_YYUIBarButtonItemBlockTarget *target = objc_getAssociatedObject(self, &block_key);
return target.block;
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIBarButtonItem+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 343
|
```objective-c
//
// UIApplication+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 13/4/4.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provides extensions for `UIApplication`.
*/
@interface UIApplication (YYAdd)
/// "Documents" folder in this app's sandbox.
@property (nonatomic, readonly) NSURL *documentsURL;
@property (nonatomic, readonly) NSString *documentsPath;
/// "Caches" folder in this app's sandbox.
@property (nonatomic, readonly) NSURL *cachesURL;
@property (nonatomic, readonly) NSString *cachesPath;
/// "Library" folder in this app's sandbox.
@property (nonatomic, readonly) NSURL *libraryURL;
@property (nonatomic, readonly) NSString *libraryPath;
/// Application's Bundle Name (show in SpringBoard).
@property (nullable, nonatomic, readonly) NSString *appBundleName;
/// Application's Bundle ID. e.g. "com.ibireme.MyApp"
@property (nullable, nonatomic, readonly) NSString *appBundleID;
/// Application's Version. e.g. "1.2.0"
@property (nullable, nonatomic, readonly) NSString *appVersion;
/// Application's Build number. e.g. "123"
@property (nullable, nonatomic, readonly) NSString *appBuildVersion;
/// Whether this app is pirated (not install from appstore).
@property (nonatomic, readonly) BOOL isPirated;
/// Whether this app is being debugged (debugger attached).
@property (nonatomic, readonly) BOOL isBeingDebugged;
/// Current thread real memory used in byte. (-1 when error occurs)
@property (nonatomic, readonly) int64_t memoryUsage;
/// Current thread CPU usage, 1.0 means 100%. (-1 when error occurs)
@property (nonatomic, readonly) float cpuUsage;
/**
Increments the number of active network requests.
If this number was zero before incrementing, this will start animating the
status bar network activity indicator.
This method is thread safe.
This method has no effect in App Extension.
*/
- (void)incrementNetworkActivityCount;
/**
Decrements the number of active network requests.
If this number becomes zero after decrementing, this will stop animating the
status bar network activity indicator.
This method is thread safe.
This method has no effect in App Extension.
*/
- (void)decrementNetworkActivityCount;
/// Returns YES in App Extension.
+ (BOOL)isAppExtension;
/// Same as sharedApplication, but returns nil in App Extension.
+ (nullable UIApplication *)sharedExtensionApplication;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIApplication+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 576
|
```objective-c
//
// UITextField+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 14/5/12.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "UITextField+YYAdd.h"
#import "YYKitMacro.h"
YYSYNTH_DUMMY_CLASS(UITextField_YYAdd)
@implementation UITextField (YYAdd)
- (void)selectAllText {
UITextRange *range = [self textRangeFromPosition:self.beginningOfDocument toPosition:self.endOfDocument];
[self setSelectedTextRange:range];
}
- (void)setSelectedRange:(NSRange)range {
UITextPosition *beginning = self.beginningOfDocument;
UITextPosition *startPosition = [self positionFromPosition:beginning offset:range.location];
UITextPosition *endPosition = [self positionFromPosition:beginning offset:NSMaxRange(range)];
UITextRange *selectionRange = [self textRangeFromPosition:startPosition toPosition:endPosition];
[self setSelectedTextRange:selectionRange];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UITextField+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 246
|
```objective-c
//
// UIGestureRecognizer+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 13/10/13.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provides extensions for `UIGestureRecognizer`.
*/
@interface UIGestureRecognizer (YYAdd)
/**
Initializes an allocated gesture-recognizer object with a action block.
@param block An action block that to handle the gesture recognized by the
receiver. nil is invalid. It is retained by the gesture.
@return An initialized instance of a concrete UIGestureRecognizer subclass or
nil if an error occurred in the attempt to initialize the object.
*/
- (instancetype)initWithActionBlock:(void (^)(id sender))block;
/**
Adds an action block to a gesture-recognizer object. It is retained by the
gesture.
@param block A block invoked by the action message. nil is not a valid value.
*/
- (void)addActionBlock:(void (^)(id sender))block;
/**
Remove all action blocks.
*/
- (void)removeAllActionBlocks;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIGestureRecognizer+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 261
|
```objective-c
//
// UIFont+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 14/5/11.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
#import <CoreGraphics/CoreGraphics.h>
#import <CoreText/CoreText.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provides extensions for `UIFont`.
*/
@interface UIFont (YYAdd) <NSCoding>
#pragma mark - Font Traits
///=============================================================================
/// @name Font Traits
///=============================================================================
@property (nonatomic, readonly) BOOL isBold NS_AVAILABLE_IOS(7_0); ///< Whether the font is bold.
@property (nonatomic, readonly) BOOL isItalic NS_AVAILABLE_IOS(7_0); ///< Whether the font is italic.
@property (nonatomic, readonly) BOOL isMonoSpace NS_AVAILABLE_IOS(7_0); ///< Whether the font is mono space.
@property (nonatomic, readonly) BOOL isColorGlyphs NS_AVAILABLE_IOS(7_0); ///< Whether the font is color glyphs (such as Emoji).
@property (nonatomic, readonly) CGFloat fontWeight NS_AVAILABLE_IOS(7_0); ///< Font weight from -1.0 to 1.0. Regular weight is 0.0.
/**
Create a bold font from receiver.
@return A bold font, or nil if failed.
*/
- (nullable UIFont *)fontWithBold NS_AVAILABLE_IOS(7_0);
/**
Create a italic font from receiver.
@return A italic font, or nil if failed.
*/
- (nullable UIFont *)fontWithItalic NS_AVAILABLE_IOS(7_0);
/**
Create a bold and italic font from receiver.
@return A bold and italic font, or nil if failed.
*/
- (nullable UIFont *)fontWithBoldItalic NS_AVAILABLE_IOS(7_0);
/**
Create a normal (no bold/italic/...) font from receiver.
@return A normal font, or nil if failed.
*/
- (nullable UIFont *)fontWithNormal NS_AVAILABLE_IOS(7_0);
#pragma mark - Create font
///=============================================================================
/// @name Create font
///=============================================================================
/**
Creates and returns a font object for the specified CTFontRef.
@param CTFont CoreText font.
*/
+ (nullable UIFont *)fontWithCTFont:(CTFontRef)CTFont;
/**
Creates and returns a font object for the specified CGFontRef and size.
@param CGFont CoreGraphic font.
@param size Font size.
*/
+ (nullable UIFont *)fontWithCGFont:(CGFontRef)CGFont size:(CGFloat)size;
/**
Creates and returns the CTFontRef object. (need call CFRelease() after used)
*/
- (nullable CTFontRef)CTFontRef CF_RETURNS_RETAINED;
/**
Creates and returns the CGFontRef object. (need call CFRelease() after used)
*/
- (nullable CGFontRef)CGFontRef CF_RETURNS_RETAINED;
#pragma mark - Load and unload font
///=============================================================================
/// @name Load and unload font
///=============================================================================
/**
Load the font from file path. Support format:TTF,OTF.
If return YES, font can be load use it PostScript Name: [UIFont fontWithName:...]
@param path font file's full path
*/
+ (BOOL)loadFontFromPath:(NSString *)path;
/**
Unload font from file path.
@param path font file's full path
*/
+ (void)unloadFontFromPath:(NSString *)path;
/**
Load the font from data. Support format:TTF,OTF.
@param data Font data.
@return UIFont object if load succeed, otherwise nil.
*/
+ (nullable UIFont *)loadFontFromData:(NSData *)data;
/**
Unload font which is loaded by loadFontFromData: function.
@param font the font loaded by loadFontFromData: function
@return YES if succeed, otherwise NO.
*/
+ (BOOL)unloadFontFromData:(UIFont *)font;
#pragma mark - Dump font data
///=============================================================================
/// @name Dump font data
///=============================================================================
/**
Serialize and return the font data.
@param font The font.
@return data in TTF, or nil if an error occurs.
*/
+ (nullable NSData *)dataFromFont:(UIFont *)font;
/**
Serialize and return the font data.
@param cgFont The font.
@return data in TTF, or nil if an error occurs.
*/
+ (nullable NSData *)dataFromCGFont:(CGFontRef)cgFont;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIFont+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 958
|
```objective-c
//
// NSKeyedUnarchiver+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 13/8/4.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provides extensions for `NSKeyedUnarchiver`.
*/
@interface NSKeyedUnarchiver (YYAdd)
/**
Same as unarchiveObjectWithData:, except it returns the exception by reference.
@param data The data need unarchived.
@param exception Pointer which will, upon return, if an exception occurred and
said pointer is not NULL, point to said NSException.
*/
+ (nullable id)unarchiveObjectWithData:(NSData *)data
exception:(NSException *_Nullable *_Nullable)exception;
/**
Same as unarchiveObjectWithFile:, except it returns the exception by reference.
@param path The path of archived object file.
@param exception Pointer which will, upon return, if an exception occurred and
said pointer is not NULL, point to said NSException.
*/
+ (nullable id)unarchiveObjectWithFile:(NSString *)path
exception:(NSException *_Nullable *_Nullable)exception;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSKeyedUnarchiver+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 286
|
```objective-c
//
// NSKeyedUnarchiver+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 13/8/4.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "NSKeyedUnarchiver+YYAdd.h"
#import "YYKitMacro.h"
YYSYNTH_DUMMY_CLASS(NSKeyedUnarchiver_YYAdd)
@implementation NSKeyedUnarchiver (YYAdd)
+ (id)unarchiveObjectWithData:(NSData *)data exception:(__autoreleasing NSException **)exception {
id object = nil;
@try {
object = [NSKeyedUnarchiver unarchiveObjectWithData:data];
}
@catch (NSException *e)
{
if (exception) *exception = e;
}
@finally
{
}
return object;
}
+ (id)unarchiveObjectWithFile:(NSString *)path exception:(__autoreleasing NSException **)exception {
id object = nil;
@try {
object = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}
@catch (NSException *e)
{
if (exception) *exception = e;
}
@finally
{
}
return object;
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSKeyedUnarchiver+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 298
|
```objective-c
//
// UIApplication+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 13/4/4.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "UIApplication+YYAdd.h"
#import "NSArray+YYAdd.h"
#import "NSObject+YYAdd.h"
#import "YYKitMacro.h"
#import "UIDevice+YYAdd.h"
#import <sys/sysctl.h>
#import <mach/mach.h>
#import <objc/runtime.h>
YYSYNTH_DUMMY_CLASS(UIApplication_YYAdd)
#define kNetworkIndicatorDelay (1/30.0)
@interface _YYUIApplicationNetworkIndicatorInfo : NSObject
@property (nonatomic, assign) NSInteger count;
@property (nonatomic, strong) NSTimer *timer;
@end
@implementation _YYUIApplicationNetworkIndicatorInfo
@end
@implementation UIApplication (YYAdd)
- (NSURL *)documentsURL {
return [[[NSFileManager defaultManager]
URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject];
}
- (NSString *)documentsPath {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
}
- (NSURL *)cachesURL {
return [[[NSFileManager defaultManager]
URLsForDirectory:NSCachesDirectory
inDomains:NSUserDomainMask] lastObject];
}
- (NSString *)cachesPath {
return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
}
- (NSURL *)libraryURL {
return [[[NSFileManager defaultManager]
URLsForDirectory:NSLibraryDirectory
inDomains:NSUserDomainMask] lastObject];
}
- (NSString *)libraryPath {
return [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
}
- (BOOL)isPirated {
if ([[UIDevice currentDevice] isSimulator]) return YES; // Simulator is not from appstore
if (getgid() <= 10) return YES; // process ID shouldn't be root
if ([[[NSBundle mainBundle] infoDictionary] objectForKey:@"SignerIdentity"]) {
return YES;
}
if (![self _yy_fileExistInMainBundle:@"_CodeSignature"]) {
return YES;
}
if (![self _yy_fileExistInMainBundle:@"SC_Info"]) {
return YES;
}
//if someone really want to crack your app, this method is useless..
//you may change this method's name, encrypt the code and do more check..
return NO;
}
- (BOOL)_yy_fileExistInMainBundle:(NSString *)name {
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *path = [NSString stringWithFormat:@"%@/%@", bundlePath, name];
return [[NSFileManager defaultManager] fileExistsAtPath:path];
}
- (NSString *)appBundleName {
return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
}
- (NSString *)appBundleID {
return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
}
- (NSString *)appVersion {
return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
}
- (NSString *)appBuildVersion {
return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
}
- (BOOL)isBeingDebugged {
size_t size = sizeof(struct kinfo_proc);
struct kinfo_proc info;
int ret = 0, name[4];
memset(&info, 0, sizeof(struct kinfo_proc));
name[0] = CTL_KERN;
name[1] = KERN_PROC;
name[2] = KERN_PROC_PID; name[3] = getpid();
if (ret == (sysctl(name, 4, &info, &size, NULL, 0))) {
return ret != 0;
}
return (info.kp_proc.p_flag & P_TRACED) ? YES : NO;
}
- (int64_t)memoryUsage {
struct task_basic_info info;
mach_msg_type_number_t size = sizeof(info);
kern_return_t kern = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &size);
if (kern != KERN_SUCCESS) return -1;
return info.resident_size;
}
- (float)cpuUsage {
kern_return_t kr;
task_info_data_t tinfo;
mach_msg_type_number_t task_info_count;
task_info_count = TASK_INFO_MAX;
kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count);
if (kr != KERN_SUCCESS) {
return -1;
}
thread_array_t thread_list;
mach_msg_type_number_t thread_count;
thread_info_data_t thinfo;
mach_msg_type_number_t thread_info_count;
thread_basic_info_t basic_info_th;
kr = task_threads(mach_task_self(), &thread_list, &thread_count);
if (kr != KERN_SUCCESS) {
return -1;
}
long tot_sec = 0;
long tot_usec = 0;
float tot_cpu = 0;
int j;
for (j = 0; j < thread_count; j++) {
thread_info_count = THREAD_INFO_MAX;
kr = thread_info(thread_list[j], THREAD_BASIC_INFO,
(thread_info_t)thinfo, &thread_info_count);
if (kr != KERN_SUCCESS) {
return -1;
}
basic_info_th = (thread_basic_info_t)thinfo;
if (!(basic_info_th->flags & TH_FLAGS_IDLE)) {
tot_sec = tot_sec + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds;
tot_usec = tot_usec + basic_info_th->system_time.microseconds + basic_info_th->system_time.microseconds;
tot_cpu = tot_cpu + basic_info_th->cpu_usage / (float)TH_USAGE_SCALE;
}
}
kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t));
assert(kr == KERN_SUCCESS);
return tot_cpu;
}
YYSYNTH_DYNAMIC_PROPERTY_OBJECT(networkActivityInfo, setNetworkActivityInfo, RETAIN_NONATOMIC, _YYUIApplicationNetworkIndicatorInfo *);
- (void)_delaySetActivity:(NSTimer *)timer {
NSNumber *visiable = timer.userInfo;
if (self.networkActivityIndicatorVisible != visiable.boolValue) {
[self setNetworkActivityIndicatorVisible:visiable.boolValue];
}
[timer invalidate];
}
- (void)_changeNetworkActivityCount:(NSInteger)delta {
@synchronized(self){
dispatch_async_on_main_queue(^{
_YYUIApplicationNetworkIndicatorInfo *info = [self networkActivityInfo];
if (!info) {
info = [_YYUIApplicationNetworkIndicatorInfo new];
[self setNetworkActivityInfo:info];
}
NSInteger count = info.count;
count += delta;
info.count = count;
[info.timer invalidate];
info.timer = [NSTimer timerWithTimeInterval:kNetworkIndicatorDelay target:self selector:@selector(_delaySetActivity:) userInfo:@(info.count > 0) repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:info.timer forMode:NSRunLoopCommonModes];
});
}
}
- (void)incrementNetworkActivityCount {
[self _changeNetworkActivityCount:1];
}
- (void)decrementNetworkActivityCount {
[self _changeNetworkActivityCount:-1];
}
+ (BOOL)isAppExtension {
static BOOL isAppExtension = NO;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class cls = NSClassFromString(@"UIApplication");
if(!cls || ![cls respondsToSelector:@selector(sharedApplication)]) isAppExtension = YES;
if ([[[NSBundle mainBundle] bundlePath] hasSuffix:@".appex"]) isAppExtension = YES;
});
return isAppExtension;
}
+ (UIApplication *)sharedExtensionApplication {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
return [self isAppExtension] ? nil : [UIApplication performSelector:@selector(sharedApplication)];
#pragma clang diagnostic pop
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/UIKit/UIApplication+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,786
|
```objective-c
//
// NSNumber+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 13/8/24.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "NSNumber+YYAdd.h"
#import "NSString+YYAdd.h"
#import "YYKitMacro.h"
YYSYNTH_DUMMY_CLASS(NSNumber_YYAdd)
@implementation NSNumber (YYAdd)
+ (NSNumber *)numberWithString:(NSString *)string {
NSString *str = [[string stringByTrim] lowercaseString];
if (!str || !str.length) {
return nil;
}
static NSDictionary *dic;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dic = @{@"true" : @(YES),
@"yes" : @(YES),
@"false" : @(NO),
@"no" : @(NO),
@"nil" : [NSNull null],
@"null" : [NSNull null],
@"<null>" : [NSNull null]};
});
id num = dic[str];
if (num) {
if (num == [NSNull null]) return nil;
return num;
}
// hex number
int sign = 0;
if ([str hasPrefix:@"0x"]) sign = 1;
else if ([str hasPrefix:@"-0x"]) sign = -1;
if (sign != 0) {
NSScanner *scan = [NSScanner scannerWithString:str];
unsigned num = -1;
BOOL suc = [scan scanHexInt:&num];
if (suc)
return [NSNumber numberWithLong:((long)num * sign)];
else
return nil;
}
// normal number
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
return [formatter numberFromString:string];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSNumber+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 434
|
```objective-c
//
// NSString+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 13/4/3.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "NSString+YYAdd.h"
#import "NSData+YYAdd.h"
#import "NSNumber+YYAdd.h"
#import "UIDevice+YYAdd.h"
#import "YYKitMacro.h"
YYSYNTH_DUMMY_CLASS(NSString_YYAdd)
@implementation NSString (YYAdd)
- (NSString *)md2String {
return [[self dataUsingEncoding:NSUTF8StringEncoding] md2String];
}
- (NSString *)md4String {
return [[self dataUsingEncoding:NSUTF8StringEncoding] md4String];
}
- (NSString *)md5String {
return [[self dataUsingEncoding:NSUTF8StringEncoding] md5String];
}
- (NSString *)sha1String {
return [[self dataUsingEncoding:NSUTF8StringEncoding] sha1String];
}
- (NSString *)sha224String {
return [[self dataUsingEncoding:NSUTF8StringEncoding] sha224String];
}
- (NSString *)sha256String {
return [[self dataUsingEncoding:NSUTF8StringEncoding] sha256String];
}
- (NSString *)sha384String {
return [[self dataUsingEncoding:NSUTF8StringEncoding] sha384String];
}
- (NSString *)sha512String {
return [[self dataUsingEncoding:NSUTF8StringEncoding] sha512String];
}
- (NSString *)crc32String {
return [[self dataUsingEncoding:NSUTF8StringEncoding] crc32String];
}
- (NSString *)hmacMD5StringWithKey:(NSString *)key {
return [[self dataUsingEncoding:NSUTF8StringEncoding]
hmacMD5StringWithKey:key];
}
- (NSString *)hmacSHA1StringWithKey:(NSString *)key {
return [[self dataUsingEncoding:NSUTF8StringEncoding]
hmacSHA1StringWithKey:key];
}
- (NSString *)hmacSHA224StringWithKey:(NSString *)key {
return [[self dataUsingEncoding:NSUTF8StringEncoding]
hmacSHA224StringWithKey:key];
}
- (NSString *)hmacSHA256StringWithKey:(NSString *)key {
return [[self dataUsingEncoding:NSUTF8StringEncoding]
hmacSHA256StringWithKey:key];
}
- (NSString *)hmacSHA384StringWithKey:(NSString *)key {
return [[self dataUsingEncoding:NSUTF8StringEncoding]
hmacSHA384StringWithKey:key];
}
- (NSString *)hmacSHA512StringWithKey:(NSString *)key {
return [[self dataUsingEncoding:NSUTF8StringEncoding]
hmacSHA512StringWithKey:key];
}
- (NSString *)base64EncodedString {
return [[self dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
}
+ (NSString *)stringWithBase64EncodedString:(NSString *)base64EncodedString {
NSData *data = [NSData dataWithBase64EncodedString:base64EncodedString];
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
- (NSString *)stringByURLEncode {
if ([self respondsToSelector:@selector(stringByAddingPercentEncodingWithAllowedCharacters:)]) {
/**
AFNetworking/AFURLRequestSerialization.m
Returns a percent-escaped string following RFC 3986 for a query string key or value.
RFC 3986 states that the following characters are "reserved" characters.
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
should be percent-escaped in the query string.
- parameter string: The string to be percent-escaped.
- returns: The percent-escaped string.
*/
static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4
static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]];
static NSUInteger const batchSize = 50;
NSUInteger index = 0;
NSMutableString *escaped = @"".mutableCopy;
while (index < self.length) {
NSUInteger length = MIN(self.length - index, batchSize);
NSRange range = NSMakeRange(index, length);
// To avoid breaking up character sequences such as
range = [self rangeOfComposedCharacterSequencesForRange:range];
NSString *substring = [self substringWithRange:range];
NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
[escaped appendString:encoded];
index += range.length;
}
return escaped;
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
CFStringEncoding cfEncoding = CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding);
NSString *encoded = (__bridge_transfer NSString *)
CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(__bridge CFStringRef)self,
NULL,
CFSTR("!#$&'()*+,/:;=?@[]"),
cfEncoding);
return encoded;
#pragma clang diagnostic pop
}
}
- (NSString *)stringByURLDecode {
if ([self respondsToSelector:@selector(stringByRemovingPercentEncoding)]) {
return [self stringByRemovingPercentEncoding];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
CFStringEncoding en = CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding);
NSString *decoded = [self stringByReplacingOccurrencesOfString:@"+"
withString:@" "];
decoded = (__bridge_transfer NSString *)
CFURLCreateStringByReplacingPercentEscapesUsingEncoding(
NULL,
(__bridge CFStringRef)decoded,
CFSTR(""),
en);
return decoded;
#pragma clang diagnostic pop
}
}
- (NSString *)stringByEscapingHTML {
NSUInteger len = self.length;
if (!len) return self;
unichar *buf = malloc(sizeof(unichar) * len);
if (!buf) return self;
[self getCharacters:buf range:NSMakeRange(0, len)];
NSMutableString *result = [NSMutableString string];
for (int i = 0; i < len; i++) {
unichar c = buf[i];
NSString *esc = nil;
switch (c) {
case 34: esc = @"""; break;
case 38: esc = @"&"; break;
case 39: esc = @"'"; break;
case 60: esc = @"<"; break;
case 62: esc = @">"; break;
default: break;
}
if (esc) {
[result appendString:esc];
} else {
CFStringAppendCharacters((CFMutableStringRef)result, &c, 1);
}
}
free(buf);
return result;
}
- (CGSize)sizeForFont:(UIFont *)font size:(CGSize)size mode:(NSLineBreakMode)lineBreakMode {
CGSize result;
if (!font) font = [UIFont systemFontOfSize:12];
if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
NSMutableDictionary *attr = [NSMutableDictionary new];
attr[NSFontAttributeName] = font;
if (lineBreakMode != NSLineBreakByWordWrapping) {
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
paragraphStyle.lineBreakMode = lineBreakMode;
attr[NSParagraphStyleAttributeName] = paragraphStyle;
}
CGRect rect = [self boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:attr context:nil];
result = rect.size;
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
result = [self sizeWithFont:font constrainedToSize:size lineBreakMode:lineBreakMode];
#pragma clang diagnostic pop
}
return result;
}
- (CGFloat)widthForFont:(UIFont *)font {
CGSize size = [self sizeForFont:font size:CGSizeMake(HUGE, HUGE) mode:NSLineBreakByWordWrapping];
return size.width;
}
- (CGFloat)heightForFont:(UIFont *)font width:(CGFloat)width {
CGSize size = [self sizeForFont:font size:CGSizeMake(width, HUGE) mode:NSLineBreakByWordWrapping];
return size.height;
}
- (BOOL)matchesRegex:(NSString *)regex options:(NSRegularExpressionOptions)options {
NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex options:options error:NULL];
if (!pattern) return NO;
return ([pattern numberOfMatchesInString:self options:0 range:NSMakeRange(0, self.length)] > 0);
}
- (void)enumerateRegexMatches:(NSString *)regex
options:(NSRegularExpressionOptions)options
usingBlock:(void (^)(NSString *match, NSRange matchRange, BOOL *stop))block {
if (regex.length == 0 || !block) return;
NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex options:options error:nil];
if (!regex) return;
[pattern enumerateMatchesInString:self options:kNilOptions range:NSMakeRange(0, self.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
block([self substringWithRange:result.range], result.range, stop);
}];
}
- (NSString *)stringByReplacingRegex:(NSString *)regex
options:(NSRegularExpressionOptions)options
withString:(NSString *)replacement; {
NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex options:options error:nil];
if (!pattern) return self;
return [pattern stringByReplacingMatchesInString:self options:0 range:NSMakeRange(0, [self length]) withTemplate:replacement];
}
- (char)charValue {
return self.numberValue.charValue;
}
- (unsigned char) unsignedCharValue {
return self.numberValue.unsignedCharValue;
}
- (short) shortValue {
return self.numberValue.shortValue;
}
- (unsigned short) unsignedShortValue {
return self.numberValue.unsignedShortValue;
}
- (unsigned int) unsignedIntValue {
return self.numberValue.unsignedIntValue;
}
- (long) longValue {
return self.numberValue.longValue;
}
- (unsigned long) unsignedLongValue {
return self.numberValue.unsignedLongValue;
}
- (unsigned long long) unsignedLongLongValue {
return self.numberValue.unsignedLongLongValue;
}
- (NSUInteger) unsignedIntegerValue {
return self.numberValue.unsignedIntegerValue;
}
+ (NSString *)stringWithUUID {
CFUUIDRef uuid = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, uuid);
CFRelease(uuid);
return (__bridge_transfer NSString *)string;
}
+ (NSString *)stringWithUTF32Char:(UTF32Char)char32 {
char32 = NSSwapHostIntToLittle(char32);
return [[NSString alloc] initWithBytes:&char32 length:4 encoding:NSUTF32LittleEndianStringEncoding];
}
+ (NSString *)stringWithUTF32Chars:(const UTF32Char *)char32 length:(NSUInteger)length {
return [[NSString alloc] initWithBytes:(const void *)char32
length:length * 4
encoding:NSUTF32LittleEndianStringEncoding];
}
- (void)enumerateUTF32CharInRange:(NSRange)range usingBlock:(void (^)(UTF32Char char32, NSRange range, BOOL *stop))block {
NSString *str = self;
if (range.location != 0 || range.length != self.length) {
str = [self substringWithRange:range];
}
NSUInteger len = [str lengthOfBytesUsingEncoding:NSUTF32StringEncoding] / 4;
UTF32Char *char32 = (UTF32Char *)[str cStringUsingEncoding:NSUTF32LittleEndianStringEncoding];
if (len == 0 || char32 == NULL) return;
NSUInteger location = 0;
BOOL stop = NO;
NSRange subRange;
UTF32Char oneChar;
for (NSUInteger i = 0; i < len; i++) {
oneChar = char32[i];
subRange = NSMakeRange(location, oneChar > 0xFFFF ? 2 : 1);
block(oneChar, subRange, &stop);
if (stop) return;
location += subRange.length;
}
}
- (NSString *)stringByTrim {
NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
return [self stringByTrimmingCharactersInSet:set];
}
- (NSString *)stringByAppendingNameScale:(CGFloat)scale {
if (fabs(scale - 1) <= __FLT_EPSILON__ || self.length == 0 || [self hasSuffix:@"/"]) return self.copy;
return [self stringByAppendingFormat:@"@%@x", @(scale)];
}
- (NSString *)stringByAppendingPathScale:(CGFloat)scale {
if (fabs(scale - 1) <= __FLT_EPSILON__ || self.length == 0 || [self hasSuffix:@"/"]) return self.copy;
NSString *ext = self.pathExtension;
NSRange extRange = NSMakeRange(self.length - ext.length, 0);
if (ext.length > 0) extRange.location -= 1;
NSString *scaleStr = [NSString stringWithFormat:@"@%@x", @(scale)];
return [self stringByReplacingCharactersInRange:extRange withString:scaleStr];
}
- (CGFloat)pathScale {
if (self.length == 0 || [self hasSuffix:@"/"]) return 1;
NSString *name = self.stringByDeletingPathExtension;
__block CGFloat scale = 1;
[name enumerateRegexMatches:@"@[0-9]+\\.?[0-9]*x$" options:NSRegularExpressionAnchorsMatchLines usingBlock: ^(NSString *match, NSRange matchRange, BOOL *stop) {
scale = [match substringWithRange:NSMakeRange(1, match.length - 2)].doubleValue;
}];
return scale;
}
- (BOOL)isNotBlank {
NSCharacterSet *blank = [NSCharacterSet whitespaceAndNewlineCharacterSet];
for (NSInteger i = 0; i < self.length; ++i) {
unichar c = [self characterAtIndex:i];
if (![blank characterIsMember:c]) {
return YES;
}
}
return NO;
}
- (BOOL)containsString:(NSString *)string {
if (string == nil) return NO;
return [self rangeOfString:string].location != NSNotFound;
}
- (BOOL)containsCharacterSet:(NSCharacterSet *)set {
if (set == nil) return NO;
return [self rangeOfCharacterFromSet:set].location != NSNotFound;
}
- (NSNumber *)numberValue {
return [NSNumber numberWithString:self];
}
- (NSData *)dataValue {
return [self dataUsingEncoding:NSUTF8StringEncoding];
}
- (NSRange)rangeOfAll {
return NSMakeRange(0, self.length);
}
- (id)jsonValueDecoded {
return [[self dataValue] jsonValueDecoded];
}
+ (NSString *)stringNamed:(NSString *)name {
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@""];
NSString *str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
if (!str) {
path = [[NSBundle mainBundle] pathForResource:name ofType:@"txt"];
str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
}
return str;
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSString+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 3,397
|
```objective-c
//
// NSObject+YYAddForKVO.m
// YYKit <path_to_url
//
// Created by ibireme on 14/10/15.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "NSObject+YYAddForKVO.h"
#import "YYKitMacro.h"
#import <objc/objc.h>
#import <objc/runtime.h>
YYSYNTH_DUMMY_CLASS(NSObject_YYAddForKVO)
static const int block_key;
@interface _YYNSObjectKVOBlockTarget : NSObject
@property (nonatomic, copy) void (^block)(__weak id obj, id oldVal, id newVal);
- (id)initWithBlock:(void (^)(__weak id obj, id oldVal, id newVal))block;
@end
@implementation _YYNSObjectKVOBlockTarget
- (id)initWithBlock:(void (^)(__weak id obj, id oldVal, id newVal))block {
self = [super init];
if (self) {
self.block = block;
}
return self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (!self.block) return;
BOOL isPrior = [[change objectForKey:NSKeyValueChangeNotificationIsPriorKey] boolValue];
if (isPrior) return;
NSKeyValueChange changeKind = [[change objectForKey:NSKeyValueChangeKindKey] integerValue];
if (changeKind != NSKeyValueChangeSetting) return;
id oldVal = [change objectForKey:NSKeyValueChangeOldKey];
if (oldVal == [NSNull null]) oldVal = nil;
id newVal = [change objectForKey:NSKeyValueChangeNewKey];
if (newVal == [NSNull null]) newVal = nil;
self.block(object, oldVal, newVal);
}
@end
@implementation NSObject (YYAddForKVO)
- (void)addObserverBlockForKeyPath:(NSString *)keyPath block:(void (^)(__weak id obj, id oldVal, id newVal))block {
if (!keyPath || !block) return;
_YYNSObjectKVOBlockTarget *target = [[_YYNSObjectKVOBlockTarget alloc] initWithBlock:block];
NSMutableDictionary *dic = [self _yy_allNSObjectObserverBlocks];
NSMutableArray *arr = dic[keyPath];
if (!arr) {
arr = [NSMutableArray new];
dic[keyPath] = arr;
}
[arr addObject:target];
[self addObserver:target forKeyPath:keyPath options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];
}
- (void)removeObserverBlocksForKeyPath:(NSString *)keyPath {
if (!keyPath) return;
NSMutableDictionary *dic = [self _yy_allNSObjectObserverBlocks];
NSMutableArray *arr = dic[keyPath];
[arr enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
[self removeObserver:obj forKeyPath:keyPath];
}];
[dic removeObjectForKey:keyPath];
}
- (void)removeObserverBlocks {
NSMutableDictionary *dic = [self _yy_allNSObjectObserverBlocks];
[dic enumerateKeysAndObjectsUsingBlock: ^(NSString *key, NSArray *arr, BOOL *stop) {
[arr enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
[self removeObserver:obj forKeyPath:key];
}];
}];
[dic removeAllObjects];
}
- (NSMutableDictionary *)_yy_allNSObjectObserverBlocks {
NSMutableDictionary *targets = objc_getAssociatedObject(self, &block_key);
if (!targets) {
targets = [NSMutableDictionary new];
objc_setAssociatedObject(self, &block_key, targets, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return targets;
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSObject+YYAddForKVO.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 816
|
```objective-c
//
// NSDictionary+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 13/4/4.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provide some some common method for `NSDictionary`.
*/
@interface NSDictionary (YYAdd)
#pragma mark - Dictionary Convertor
///=============================================================================
/// @name Dictionary Convertor
///=============================================================================
/**
Creates and returns a dictionary from a specified property list data.
@param plist A property list data whose root object is a dictionary.
@return A new dictionary created from the binary plist data, or nil if an error occurs.
*/
+ (nullable NSDictionary *)dictionaryWithPlistData:(NSData *)plist;
/**
Creates and returns a dictionary from a specified property list xml string.
@param plist A property list xml string whose root object is a dictionary.
@return A new dictionary created from the plist string, or nil if an error occurs.
@discussion Apple has implemented this method, but did not make it public.
*/
+ (nullable NSDictionary *)dictionaryWithPlistString:(NSString *)plist;
/**
Serialize the dictionary to a binary property list data.
@return A binary plist data, or nil if an error occurs.
@discussion Apple has implemented this method, but did not make it public.
*/
- (nullable NSData *)plistData;
/**
Serialize the dictionary to a xml property list string.
@return A plist xml string, or nil if an error occurs.
*/
- (nullable NSString *)plistString;
/**
Returns a new array containing the dictionary's keys sorted.
The keys should be NSString, and they will be sorted ascending.
@return A new array containing the dictionary's keys,
or an empty array if the dictionary has no entries.
*/
- (NSArray *)allKeysSorted;
/**
Returns a new array containing the dictionary's values sorted by keys.
The order of the values in the array is defined by keys.
The keys should be NSString, and they will be sorted ascending.
@return A new array containing the dictionary's values sorted by keys,
or an empty array if the dictionary has no entries.
*/
- (NSArray *)allValuesSortedByKeys;
/**
Returns a BOOL value tells if the dictionary has an object for key.
@param key The key.
*/
- (BOOL)containsObjectForKey:(id)key;
/**
Returns a new dictionary containing the entries for keys.
If the keys is empty or nil, it just returns an empty dictionary.
@param keys The keys.
@return The entries for the keys.
*/
- (NSDictionary *)entriesForKeys:(NSArray *)keys;
/**
Convert dictionary to json string. return nil if an error occurs.
*/
- (nullable NSString *)jsonStringEncoded;
/**
Convert dictionary to json string formatted. return nil if an error occurs.
*/
- (nullable NSString *)jsonPrettyStringEncoded;
/**
Try to parse an XML and wrap it into a dictionary.
If you just want to get some value from a small xml, try this.
example XML: "<config><a href="test.com">link</a></config>"
example Return: @{@"_name":@"config", @"a":{@"_text":@"link",@"href":@"test.com"}}
@param xmlDataOrString XML in NSData or NSString format.
@return Return a new dictionary, or nil if an error occurs.
*/
+ (nullable NSDictionary *)dictionaryWithXML:(id)xmlDataOrString;
#pragma mark - Dictionary Value Getter
///=============================================================================
/// @name Dictionary Value Getter
///=============================================================================
- (BOOL)boolValueForKey:(NSString *)key default:(BOOL)def;
- (char)charValueForKey:(NSString *)key default:(char)def;
- (unsigned char)unsignedCharValueForKey:(NSString *)key default:(unsigned char)def;
- (short)shortValueForKey:(NSString *)key default:(short)def;
- (unsigned short)unsignedShortValueForKey:(NSString *)key default:(unsigned short)def;
- (int)intValueForKey:(NSString *)key default:(int)def;
- (unsigned int)unsignedIntValueForKey:(NSString *)key default:(unsigned int)def;
- (long)longValueForKey:(NSString *)key default:(long)def;
- (unsigned long)unsignedLongValueForKey:(NSString *)key default:(unsigned long)def;
- (long long)longLongValueForKey:(NSString *)key default:(long long)def;
- (unsigned long long)unsignedLongLongValueForKey:(NSString *)key default:(unsigned long long)def;
- (float)floatValueForKey:(NSString *)key default:(float)def;
- (double)doubleValueForKey:(NSString *)key default:(double)def;
- (NSInteger)integerValueForKey:(NSString *)key default:(NSInteger)def;
- (NSUInteger)unsignedIntegerValueForKey:(NSString *)key default:(NSUInteger)def;
- (nullable NSNumber *)numberValueForKey:(NSString *)key default:(nullable NSNumber *)def;
- (nullable NSString *)stringValueForKey:(NSString *)key default:(nullable NSString *)def;
@end
/**
Provide some some common method for `NSMutableDictionary`.
*/
@interface NSMutableDictionary (YYAdd)
/**
Creates and returns a dictionary from a specified property list data.
@param plist A property list data whose root object is a dictionary.
@return A new dictionary created from the binary plist data, or nil if an error occurs.
@discussion Apple has implemented this method, but did not make it public.
*/
+ (nullable NSMutableDictionary *)dictionaryWithPlistData:(NSData *)plist;
/**
Creates and returns a dictionary from a specified property list xml string.
@param plist A property list xml string whose root object is a dictionary.
@return A new dictionary created from the plist string, or nil if an error occurs.
*/
+ (nullable NSMutableDictionary *)dictionaryWithPlistString:(NSString *)plist;
/**
Removes and returns the value associated with a given key.
@param aKey The key for which to return and remove the corresponding value.
@return The value associated with aKey, or nil if no value is associated with aKey.
*/
- (nullable id)popObjectForKey:(id)aKey;
/**
Returns a new dictionary containing the entries for keys, and remove these
entries from receiver. If the keys is empty or nil, it just returns an
empty dictionary.
@param keys The keys.
@return The entries for the keys.
*/
- (NSDictionary *)popEntriesForKeys:(NSArray *)keys;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSDictionary+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,368
|
```objective-c
//
// NSNotificationCenter+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 13/8/24.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "NSNotificationCenter+YYAdd.h"
#include <pthread.h>
#import "YYKitMacro.h"
YYSYNTH_DUMMY_CLASS(NSNotificationCenter_YYAdd)
@implementation NSNotificationCenter (YYAdd)
- (void)postNotificationOnMainThread:(NSNotification *)notification {
if (pthread_main_np()) return [self postNotification:notification];
[self postNotificationOnMainThread:notification waitUntilDone:NO];
}
- (void)postNotificationOnMainThread:(NSNotification *)notification waitUntilDone:(BOOL)wait {
if (pthread_main_np()) return [self postNotification:notification];
[[self class] performSelectorOnMainThread:@selector(_yy_postNotification:) withObject:notification waitUntilDone:wait];
}
- (void)postNotificationOnMainThreadWithName:(NSString *)name object:(id)object {
if (pthread_main_np()) return [self postNotificationName:name object:object userInfo:nil];
[self postNotificationOnMainThreadWithName:name object:object userInfo:nil waitUntilDone:NO];
}
- (void)postNotificationOnMainThreadWithName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo {
if (pthread_main_np()) return [self postNotificationName:name object:object userInfo:userInfo];
[self postNotificationOnMainThreadWithName:name object:object userInfo:userInfo waitUntilDone:NO];
}
- (void)postNotificationOnMainThreadWithName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo waitUntilDone:(BOOL)wait {
if (pthread_main_np()) return [self postNotificationName:name object:object userInfo:userInfo];
NSMutableDictionary *info = [[NSMutableDictionary allocWithZone:nil] initWithCapacity:3];
if (name) [info setObject:name forKey:@"name"];
if (object) [info setObject:object forKey:@"object"];
if (userInfo) [info setObject:userInfo forKey:@"userInfo"];
[[self class] performSelectorOnMainThread:@selector(_yy_postNotificationName:) withObject:info waitUntilDone:wait];
}
+ (void)_yy_postNotification:(NSNotification *)notification {
[[self defaultCenter] postNotification:notification];
}
+ (void)_yy_postNotificationName:(NSDictionary *)info {
NSString *name = [info objectForKey:@"name"];
id object = [info objectForKey:@"object"];
NSDictionary *userInfo = [info objectForKey:@"userInfo"];
[[self defaultCenter] postNotificationName:name object:object userInfo:userInfo];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSNotificationCenter+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 558
|
```objective-c
//
// NSBundle+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 14/10/20.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "NSBundle+YYAdd.h"
#import "NSString+YYAdd.h"
#import "YYKitMacro.h"
YYSYNTH_DUMMY_CLASS(NSBundle_YYAdd)
@implementation NSBundle (YYAdd)
+ (NSArray *)preferredScales {
static NSArray *scales;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
CGFloat screenScale = [UIScreen mainScreen].scale;
if (screenScale <= 1) {
scales = @[@1,@2,@3];
} else if (screenScale <= 2) {
scales = @[@2,@3,@1];
} else {
scales = @[@3,@2,@1];
}
});
return scales;
}
+ (NSString *)pathForScaledResource:(NSString *)name ofType:(NSString *)ext inDirectory:(NSString *)bundlePath {
if (name.length == 0) return nil;
if ([name hasSuffix:@"/"]) return [self pathForResource:name ofType:ext inDirectory:bundlePath];
NSString *path = nil;
NSArray *scales = [self preferredScales];
for (int s = 0; s < scales.count; s++) {
CGFloat scale = ((NSNumber *)scales[s]).floatValue;
NSString *scaledName = ext.length ? [name stringByAppendingNameScale:scale]
: [name stringByAppendingPathScale:scale];
path = [self pathForResource:scaledName ofType:ext inDirectory:bundlePath];
if (path) break;
}
return path;
}
- (NSString *)pathForScaledResource:(NSString *)name ofType:(NSString *)ext {
if (name.length == 0) return nil;
if ([name hasSuffix:@"/"]) return [self pathForResource:name ofType:ext];
NSString *path = nil;
NSArray *scales = [NSBundle preferredScales];
for (int s = 0; s < scales.count; s++) {
CGFloat scale = ((NSNumber *)scales[s]).floatValue;
NSString *scaledName = ext.length ? [name stringByAppendingNameScale:scale]
: [name stringByAppendingPathScale:scale];
path = [self pathForResource:scaledName ofType:ext];
if (path) break;
}
return path;
}
- (NSString *)pathForScaledResource:(NSString *)name ofType:(NSString *)ext inDirectory:(NSString *)subpath {
if (name.length == 0) return nil;
if ([name hasSuffix:@"/"]) return [self pathForResource:name ofType:ext];
NSString *path = nil;
NSArray *scales = [NSBundle preferredScales];
for (int s = 0; s < scales.count; s++) {
CGFloat scale = ((NSNumber *)scales[s]).floatValue;
NSString *scaledName = ext.length ? [name stringByAppendingNameScale:scale]
: [name stringByAppendingPathScale:scale];
path = [self pathForResource:scaledName ofType:ext inDirectory:subpath];
if (path) break;
}
return path;
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSBundle+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 719
|
```objective-c
//
// NSNumber+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 13/8/24.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provide a method to parse `NSString` for `NSNumber`.
*/
@interface NSNumber (YYAdd)
/**
Creates and returns an NSNumber object from a string.
Valid format: @"12", @"12.345", @" -0xFF", @" .23e99 "...
@param string The string described an number.
@return an NSNumber when parse succeed, or nil if an error occurs.
*/
+ (nullable NSNumber *)numberWithString:(NSString *)string;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSNumber+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 178
|
```objective-c
//
// NSData+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 13/4/4.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "NSData+YYAdd.h"
#import "YYKitMacro.h"
#include <CommonCrypto/CommonCrypto.h>
#include <zlib.h>
YYSYNTH_DUMMY_CLASS(NSData_YYAdd)
@implementation NSData (YYAdd)
- (NSString *)md2String {
unsigned char result[CC_MD2_DIGEST_LENGTH];
CC_MD2(self.bytes, (CC_LONG)self.length, result);
return [NSString stringWithFormat:
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
}
- (NSData *)md2Data {
unsigned char result[CC_MD2_DIGEST_LENGTH];
CC_MD2(self.bytes, (CC_LONG)self.length, result);
return [NSData dataWithBytes:result length:CC_MD2_DIGEST_LENGTH];
}
- (NSString *)md4String {
unsigned char result[CC_MD4_DIGEST_LENGTH];
CC_MD4(self.bytes, (CC_LONG)self.length, result);
return [NSString stringWithFormat:
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
}
- (NSData *)md4Data {
unsigned char result[CC_MD4_DIGEST_LENGTH];
CC_MD4(self.bytes, (CC_LONG)self.length, result);
return [NSData dataWithBytes:result length:CC_MD4_DIGEST_LENGTH];
}
- (NSString *)md5String {
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(self.bytes, (CC_LONG)self.length, result);
return [NSString stringWithFormat:
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
}
- (NSData *)md5Data {
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(self.bytes, (CC_LONG)self.length, result);
return [NSData dataWithBytes:result length:CC_MD5_DIGEST_LENGTH];
}
- (NSString *)sha1String {
unsigned char result[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(self.bytes, (CC_LONG)self.length, result);
NSMutableString *hash = [NSMutableString
stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
[hash appendFormat:@"%02x", result[i]];
}
return hash;
}
- (NSData *)sha1Data {
unsigned char result[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(self.bytes, (CC_LONG)self.length, result);
return [NSData dataWithBytes:result length:CC_SHA1_DIGEST_LENGTH];
}
- (NSString *)sha224String {
unsigned char result[CC_SHA224_DIGEST_LENGTH];
CC_SHA224(self.bytes, (CC_LONG)self.length, result);
NSMutableString *hash = [NSMutableString
stringWithCapacity:CC_SHA224_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_SHA224_DIGEST_LENGTH; i++) {
[hash appendFormat:@"%02x", result[i]];
}
return hash;
}
- (NSData *)sha224Data {
unsigned char result[CC_SHA224_DIGEST_LENGTH];
CC_SHA224(self.bytes, (CC_LONG)self.length, result);
return [NSData dataWithBytes:result length:CC_SHA224_DIGEST_LENGTH];
}
- (NSString *)sha256String {
unsigned char result[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(self.bytes, (CC_LONG)self.length, result);
NSMutableString *hash = [NSMutableString
stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
[hash appendFormat:@"%02x", result[i]];
}
return hash;
}
- (NSData *)sha256Data {
unsigned char result[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(self.bytes, (CC_LONG)self.length, result);
return [NSData dataWithBytes:result length:CC_SHA256_DIGEST_LENGTH];
}
- (NSString *)sha384String {
unsigned char result[CC_SHA384_DIGEST_LENGTH];
CC_SHA384(self.bytes, (CC_LONG)self.length, result);
NSMutableString *hash = [NSMutableString
stringWithCapacity:CC_SHA384_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_SHA384_DIGEST_LENGTH; i++) {
[hash appendFormat:@"%02x", result[i]];
}
return hash;
}
- (NSData *)sha384Data {
unsigned char result[CC_SHA384_DIGEST_LENGTH];
CC_SHA384(self.bytes, (CC_LONG)self.length, result);
return [NSData dataWithBytes:result length:CC_SHA384_DIGEST_LENGTH];
}
- (NSString *)sha512String {
unsigned char result[CC_SHA512_DIGEST_LENGTH];
CC_SHA512(self.bytes, (CC_LONG)self.length, result);
NSMutableString *hash = [NSMutableString
stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++) {
[hash appendFormat:@"%02x", result[i]];
}
return hash;
}
- (NSData *)sha512Data {
unsigned char result[CC_SHA512_DIGEST_LENGTH];
CC_SHA512(self.bytes, (CC_LONG)self.length, result);
return [NSData dataWithBytes:result length:CC_SHA512_DIGEST_LENGTH];
}
- (NSString *)hmacStringUsingAlg:(CCHmacAlgorithm)alg withKey:(NSString *)key {
size_t size;
switch (alg) {
case kCCHmacAlgMD5: size = CC_MD5_DIGEST_LENGTH; break;
case kCCHmacAlgSHA1: size = CC_SHA1_DIGEST_LENGTH; break;
case kCCHmacAlgSHA224: size = CC_SHA224_DIGEST_LENGTH; break;
case kCCHmacAlgSHA256: size = CC_SHA256_DIGEST_LENGTH; break;
case kCCHmacAlgSHA384: size = CC_SHA384_DIGEST_LENGTH; break;
case kCCHmacAlgSHA512: size = CC_SHA512_DIGEST_LENGTH; break;
default: return nil;
}
unsigned char result[size];
const char *cKey = [key cStringUsingEncoding:NSUTF8StringEncoding];
CCHmac(alg, cKey, strlen(cKey), self.bytes, self.length, result);
NSMutableString *hash = [NSMutableString stringWithCapacity:size * 2];
for (int i = 0; i < size; i++) {
[hash appendFormat:@"%02x", result[i]];
}
return hash;
}
- (NSData *)hmacDataUsingAlg:(CCHmacAlgorithm)alg withKey:(NSData *)key {
size_t size;
switch (alg) {
case kCCHmacAlgMD5: size = CC_MD5_DIGEST_LENGTH; break;
case kCCHmacAlgSHA1: size = CC_SHA1_DIGEST_LENGTH; break;
case kCCHmacAlgSHA224: size = CC_SHA224_DIGEST_LENGTH; break;
case kCCHmacAlgSHA256: size = CC_SHA256_DIGEST_LENGTH; break;
case kCCHmacAlgSHA384: size = CC_SHA384_DIGEST_LENGTH; break;
case kCCHmacAlgSHA512: size = CC_SHA512_DIGEST_LENGTH; break;
default: return nil;
}
unsigned char result[size];
CCHmac(alg, [key bytes], key.length, self.bytes, self.length, result);
return [NSData dataWithBytes:result length:size];
}
- (NSString *)hmacMD5StringWithKey:(NSString *)key {
return [self hmacStringUsingAlg:kCCHmacAlgMD5 withKey:key];
}
- (NSData *)hmacMD5DataWithKey:(NSData *)key {
return [self hmacDataUsingAlg:kCCHmacAlgMD5 withKey:key];
}
- (NSString *)hmacSHA1StringWithKey:(NSString *)key {
return [self hmacStringUsingAlg:kCCHmacAlgSHA1 withKey:key];
}
- (NSData *)hmacSHA1DataWithKey:(NSData *)key {
return [self hmacDataUsingAlg:kCCHmacAlgSHA1 withKey:key];
}
- (NSString *)hmacSHA224StringWithKey:(NSString *)key {
return [self hmacStringUsingAlg:kCCHmacAlgSHA224 withKey:key];
}
- (NSData *)hmacSHA224DataWithKey:(NSData *)key {
return [self hmacDataUsingAlg:kCCHmacAlgSHA224 withKey:key];
}
- (NSString *)hmacSHA256StringWithKey:(NSString *)key {
return [self hmacStringUsingAlg:kCCHmacAlgSHA256 withKey:key];
}
- (NSData *)hmacSHA256DataWithKey:(NSData *)key {
return [self hmacDataUsingAlg:kCCHmacAlgSHA256 withKey:key];
}
- (NSString *)hmacSHA384StringWithKey:(NSString *)key {
return [self hmacStringUsingAlg:kCCHmacAlgSHA384 withKey:key];
}
- (NSData *)hmacSHA384DataWithKey:(NSData *)key {
return [self hmacDataUsingAlg:kCCHmacAlgSHA384 withKey:key];
}
- (NSString *)hmacSHA512StringWithKey:(NSString *)key {
return [self hmacStringUsingAlg:kCCHmacAlgSHA512 withKey:key];
}
- (NSData *)hmacSHA512DataWithKey:(NSData *)key {
return [self hmacDataUsingAlg:kCCHmacAlgSHA512 withKey:key];
}
- (NSString *)crc32String {
uLong result = crc32(0, self.bytes, (uInt)self.length);
return [NSString stringWithFormat:@"%08x", (uint32_t)result];
}
- (uint32_t)crc32 {
uLong result = crc32(0, self.bytes, (uInt)self.length);
return (uint32_t)result;
}
- (NSData *)aes256EncryptWithKey:(NSData *)key iv:(NSData *)iv {
if (key.length != 16 && key.length != 24 && key.length != 32) {
return nil;
}
if (iv.length != 16 && iv.length != 0) {
return nil;
}
NSData *result = nil;
size_t bufferSize = self.length + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
if (!buffer) return nil;
size_t encryptedSize = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
key.bytes,
key.length,
iv.bytes,
self.bytes,
self.length,
buffer,
bufferSize,
&encryptedSize);
if (cryptStatus == kCCSuccess) {
result = [[NSData alloc]initWithBytes:buffer length:encryptedSize];
free(buffer);
return result;
} else {
free(buffer);
return nil;
}
}
- (NSData *)aes256DecryptWithkey:(NSData *)key iv:(NSData *)iv {
if (key.length != 16 && key.length != 24 && key.length != 32) {
return nil;
}
if (iv.length != 16 && iv.length != 0) {
return nil;
}
NSData *result = nil;
size_t bufferSize = self.length + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
if (!buffer) return nil;
size_t encryptedSize = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
key.bytes,
key.length,
iv.bytes,
self.bytes,
self.length,
buffer,
bufferSize,
&encryptedSize);
if (cryptStatus == kCCSuccess) {
result = [[NSData alloc]initWithBytes:buffer length:encryptedSize];
free(buffer);
return result;
} else {
free(buffer);
return nil;
}
}
- (NSString *)utf8String {
if (self.length > 0) {
return [[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding];
}
return @"";
}
- (NSString *)hexString {
NSUInteger length = self.length;
NSMutableString *result = [NSMutableString stringWithCapacity:length * 2];
const unsigned char *byte = self.bytes;
for (int i = 0; i < length; i++, byte++) {
[result appendFormat:@"%02X", *byte];
}
return result;
}
+ (NSData *)dataWithHexString:(NSString *)hexStr {
hexStr = [hexStr stringByReplacingOccurrencesOfString:@" " withString:@""];
hexStr = [hexStr lowercaseString];
NSUInteger len = hexStr.length;
if (!len) return nil;
unichar *buf = malloc(sizeof(unichar) * len);
if (!buf) return nil;
[hexStr getCharacters:buf range:NSMakeRange(0, len)];
NSMutableData *result = [NSMutableData data];
unsigned char bytes;
char str[3] = { '\0', '\0', '\0' };
int i;
for (i = 0; i < len / 2; i++) {
str[0] = buf[i * 2];
str[1] = buf[i * 2 + 1];
bytes = strtol(str, NULL, 16);
[result appendBytes:&bytes length:1];
}
free(buf);
return result;
}
static const char base64EncodingTable[64]
= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const short base64DecodingTable[256] = {
-2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -1, -2, -1, -1, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 62, -2, -2, -2, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -2, -2, -2, -2, -2, -2,
-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -2, -2, -2, -2, -2,
-2, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2
};
- (NSString *)base64EncodedString {
NSUInteger length = self.length;
if (length == 0)
return @"";
NSUInteger out_length = ((length + 2) / 3) * 4;
uint8_t *output = malloc(((out_length + 2) / 3) * 4);
if (output == NULL)
return nil;
const char *input = self.bytes;
NSInteger i, value;
for (i = 0; i < length; i += 3) {
value = 0;
for (NSInteger j = i; j < i + 3; j++) {
value <<= 8;
if (j < length) {
value |= (0xFF & input[j]);
}
}
NSInteger index = (i / 3) * 4;
output[index + 0] = base64EncodingTable[(value >> 18) & 0x3F];
output[index + 1] = base64EncodingTable[(value >> 12) & 0x3F];
output[index + 2] = ((i + 1) < length)
? base64EncodingTable[(value >> 6) & 0x3F]
: '=';
output[index + 3] = ((i + 2) < length)
? base64EncodingTable[(value >> 0) & 0x3F]
: '=';
}
NSString *base64 = [[NSString alloc] initWithBytes:output
length:out_length
encoding:NSASCIIStringEncoding];
free(output);
return base64;
}
+ (NSData *)dataWithBase64EncodedString:(NSString *)base64EncodedString {
NSInteger length = base64EncodedString.length;
const char *string = [base64EncodedString cStringUsingEncoding:NSASCIIStringEncoding];
if (string == NULL)
return nil;
while (length > 0 && string[length - 1] == '=')
length--;
NSInteger outputLength = length * 3 / 4;
NSMutableData *data = [NSMutableData dataWithLength:outputLength];
if (data == nil)
return nil;
if (length == 0)
return data;
uint8_t *output = data.mutableBytes;
NSInteger inputPoint = 0;
NSInteger outputPoint = 0;
while (inputPoint < length) {
char i0 = string[inputPoint++];
char i1 = string[inputPoint++];
char i2 = inputPoint < length ? string[inputPoint++] : 'A';
char i3 = inputPoint < length ? string[inputPoint++] : 'A';
output[outputPoint++] = (base64DecodingTable[i0] << 2)
| (base64DecodingTable[i1] >> 4);
if (outputPoint < outputLength) {
output[outputPoint++] = ((base64DecodingTable[i1] & 0xf) << 4)
| (base64DecodingTable[i2] >> 2);
}
if (outputPoint < outputLength) {
output[outputPoint++] = ((base64DecodingTable[i2] & 0x3) << 6)
| base64DecodingTable[i3];
}
}
return data;
}
- (id)jsonValueDecoded {
NSError *error = nil;
id value = [NSJSONSerialization JSONObjectWithData:self options:kNilOptions error:&error];
if (error) {
NSLog(@"jsonValueDecoded error:%@", error);
}
return value;
}
- (NSData *)gzipInflate {
if ([self length] == 0) return self;
unsigned full_length = (unsigned)[self length];
unsigned half_length = (unsigned)[self length] / 2;
NSMutableData *decompressed = [NSMutableData
dataWithLength:full_length + half_length];
BOOL done = NO;
int status;
z_stream strm;
strm.next_in = (Bytef *)[self bytes];
strm.avail_in = (unsigned)[self length];
strm.total_out = 0;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
if (inflateInit2(&strm, (15 + 32)) != Z_OK) return nil;
while (!done) {
// Make sure we have enough room and reset the lengths.
if (strm.total_out >= [decompressed length])
[decompressed increaseLengthBy:half_length];
strm.next_out = [decompressed mutableBytes] + strm.total_out;
strm.avail_out = (uInt)([decompressed length] - strm.total_out);
// Inflate another chunk.
status = inflate(&strm, Z_SYNC_FLUSH);
if (status == Z_STREAM_END) done = YES;
else if (status != Z_OK) break;
}
if (inflateEnd(&strm) != Z_OK) return nil;
// Set real length.
if (done) {
[decompressed setLength:strm.total_out];
return [NSData dataWithData:decompressed];
} else return nil;
}
- (NSData *)gzipDeflate {
if ([self length] == 0) return self;
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.total_out = 0;
strm.next_in = (Bytef *)[self bytes];
strm.avail_in = (uInt)[self length];
// Compresssion Levels:
// Z_NO_COMPRESSION
// Z_BEST_SPEED
// Z_BEST_COMPRESSION
// Z_DEFAULT_COMPRESSION
if (deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (15 + 16),
8, Z_DEFAULT_STRATEGY) != Z_OK)
return nil;
// 16K chunks for expansion
NSMutableData *compressed = [NSMutableData dataWithLength:16384];
do {
if (strm.total_out >= [compressed length])
[compressed increaseLengthBy:16384];
strm.next_out = [compressed mutableBytes] + strm.total_out;
strm.avail_out = (uInt)([compressed length] - strm.total_out);
deflate(&strm, Z_FINISH);
}
while (strm.avail_out == 0);
deflateEnd(&strm);
[compressed setLength:strm.total_out];
return [NSData dataWithData:compressed];
}
- (NSData *)zlibInflate {
if ([self length] == 0) return self;
NSUInteger full_length = [self length];
NSUInteger half_length = [self length] / 2;
NSMutableData *decompressed = [NSMutableData
dataWithLength:full_length + half_length];
BOOL done = NO;
int status;
z_stream strm;
strm.next_in = (Bytef *)[self bytes];
strm.avail_in = (uInt)full_length;
strm.total_out = 0;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
if (inflateInit(&strm) != Z_OK) return nil;
while (!done) {
// Make sure we have enough room and reset the lengths.
if (strm.total_out >= [decompressed length])
[decompressed increaseLengthBy:half_length];
strm.next_out = [decompressed mutableBytes] + strm.total_out;
strm.avail_out = (uInt)([decompressed length] - strm.total_out);
// Inflate another chunk.
status = inflate(&strm, Z_SYNC_FLUSH);
if (status == Z_STREAM_END) done = YES;
else if (status != Z_OK) break;
}
if (inflateEnd(&strm) != Z_OK) return nil;
// Set real length.
if (done) {
[decompressed setLength:strm.total_out];
return [NSData dataWithData:decompressed];
} else return nil;
}
- (NSData *)zlibDeflate {
if ([self length] == 0) return self;
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.total_out = 0;
strm.next_in = (Bytef *)[self bytes];
strm.avail_in = (uInt)[self length];
// Compresssion Levels:
// Z_NO_COMPRESSION
// Z_BEST_SPEED
// Z_BEST_COMPRESSION
// Z_DEFAULT_COMPRESSION
if (deflateInit(&strm, Z_DEFAULT_COMPRESSION) != Z_OK) return nil;
// 16K chuncks for expansion
NSMutableData *compressed = [NSMutableData dataWithLength:16384];
do {
if (strm.total_out >= [compressed length])
[compressed increaseLengthBy:16384];
strm.next_out = [compressed mutableBytes] + strm.total_out;
strm.avail_out = (uInt)([compressed length] - strm.total_out);
deflate(&strm, Z_FINISH);
}
while (strm.avail_out == 0);
deflateEnd(&strm);
[compressed setLength:strm.total_out];
return [NSData dataWithData:compressed];
}
+ (NSData *)dataNamed:(NSString *)name {
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@""];
if (!path) return nil;
NSData *data = [NSData dataWithContentsOfFile:path];
return data;
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSData+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 6,228
|
```objective-c
//
// NSDate+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 13/4/11.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "NSDate+YYAdd.h"
#import "YYKitMacro.h"
#import <time.h>
YYSYNTH_DUMMY_CLASS(NSDate_YYAdd)
@implementation NSDate (YYAdd)
- (NSInteger)year {
return [[[NSCalendar currentCalendar] components:NSCalendarUnitYear fromDate:self] year];
}
- (NSInteger)month {
return [[[NSCalendar currentCalendar] components:NSCalendarUnitMonth fromDate:self] month];
}
- (NSInteger)day {
return [[[NSCalendar currentCalendar] components:NSCalendarUnitDay fromDate:self] day];
}
- (NSInteger)hour {
return [[[NSCalendar currentCalendar] components:NSCalendarUnitHour fromDate:self] hour];
}
- (NSInteger)minute {
return [[[NSCalendar currentCalendar] components:NSCalendarUnitMinute fromDate:self] minute];
}
- (NSInteger)second {
return [[[NSCalendar currentCalendar] components:NSCalendarUnitSecond fromDate:self] second];
}
- (NSInteger)nanosecond {
return [[[NSCalendar currentCalendar] components:NSCalendarUnitSecond fromDate:self] nanosecond];
}
- (NSInteger)weekday {
return [[[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:self] weekday];
}
- (NSInteger)weekdayOrdinal {
return [[[NSCalendar currentCalendar] components:NSCalendarUnitWeekdayOrdinal fromDate:self] weekdayOrdinal];
}
- (NSInteger)weekOfMonth {
return [[[NSCalendar currentCalendar] components:NSCalendarUnitWeekOfMonth fromDate:self] weekOfMonth];
}
- (NSInteger)weekOfYear {
return [[[NSCalendar currentCalendar] components:NSCalendarUnitWeekOfYear fromDate:self] weekOfYear];
}
- (NSInteger)yearForWeekOfYear {
return [[[NSCalendar currentCalendar] components:NSCalendarUnitYearForWeekOfYear fromDate:self] yearForWeekOfYear];
}
- (NSInteger)quarter {
return [[[NSCalendar currentCalendar] components:NSCalendarUnitQuarter fromDate:self] quarter];
}
- (BOOL)isLeapMonth {
return [[[NSCalendar currentCalendar] components:NSCalendarUnitQuarter fromDate:self] isLeapMonth];
}
- (BOOL)isLeapYear {
NSUInteger year = self.year;
return ((year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0)));
}
- (BOOL)isToday {
if (fabs(self.timeIntervalSinceNow) >= 60 * 60 * 24) return NO;
return [NSDate new].day == self.day;
}
- (BOOL)isYesterday {
NSDate *added = [self dateByAddingDays:1];
return [added isToday];
}
- (NSDate *)dateByAddingYears:(NSInteger)years {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:years];
return [calendar dateByAddingComponents:components toDate:self options:0];
}
- (NSDate *)dateByAddingMonths:(NSInteger)months {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setMonth:months];
return [calendar dateByAddingComponents:components toDate:self options:0];
}
- (NSDate *)dateByAddingWeeks:(NSInteger)weeks {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setWeekOfYear:weeks];
return [calendar dateByAddingComponents:components toDate:self options:0];
}
- (NSDate *)dateByAddingDays:(NSInteger)days {
NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + 86400 * days;
NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
return newDate;
}
- (NSDate *)dateByAddingHours:(NSInteger)hours {
NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + 3600 * hours;
NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
return newDate;
}
- (NSDate *)dateByAddingMinutes:(NSInteger)minutes {
NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + 60 * minutes;
NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
return newDate;
}
- (NSDate *)dateByAddingSeconds:(NSInteger)seconds {
NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + seconds;
NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
return newDate;
}
- (NSString *)stringWithFormat:(NSString *)format {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:format];
[formatter setLocale:[NSLocale currentLocale]];
return [formatter stringFromDate:self];
}
- (NSString *)stringWithFormat:(NSString *)format timeZone:(NSTimeZone *)timeZone locale:(NSLocale *)locale {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:format];
if (timeZone) [formatter setTimeZone:timeZone];
if (locale) [formatter setLocale:locale];
return [formatter stringFromDate:self];
}
- (NSString *)stringWithISOFormat {
static NSDateFormatter *formatter = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
formatter = [[NSDateFormatter alloc] init];
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ";
});
return [formatter stringFromDate:self];
}
+ (NSDate *)dateWithString:(NSString *)dateString format:(NSString *)format {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:format];
return [formatter dateFromString:dateString];
}
+ (NSDate *)dateWithString:(NSString *)dateString format:(NSString *)format timeZone:(NSTimeZone *)timeZone locale:(NSLocale *)locale {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:format];
if (timeZone) [formatter setTimeZone:timeZone];
if (locale) [formatter setLocale:locale];
return [formatter dateFromString:dateString];
}
+ (NSDate *)dateWithISOFormatString:(NSString *)dateString {
static NSDateFormatter *formatter = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
formatter = [[NSDateFormatter alloc] init];
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ";
});
return [formatter dateFromString:dateString];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSDate+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,467
|
```objective-c
//
// NSArray+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 13/4/4.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "NSArray+YYAdd.h"
#import "YYKitMacro.h"
#import "NSData+YYAdd.h"
YYSYNTH_DUMMY_CLASS(NSArray_YYAdd)
@implementation NSArray (YYAdd)
+ (NSArray *)arrayWithPlistData:(NSData *)plist {
if (!plist) return nil;
NSArray *array = [NSPropertyListSerialization propertyListWithData:plist options:NSPropertyListImmutable format:NULL error:NULL];
if ([array isKindOfClass:[NSArray class]]) return array;
return nil;
}
+ (NSArray *)arrayWithPlistString:(NSString *)plist {
if (!plist) return nil;
NSData *data = [plist dataUsingEncoding:NSUTF8StringEncoding];
return [self arrayWithPlistData:data];
}
- (NSData *)plistData {
return [NSPropertyListSerialization dataWithPropertyList:self format:NSPropertyListBinaryFormat_v1_0 options:kNilOptions error:NULL];
}
- (NSString *)plistString {
NSData *xmlData = [NSPropertyListSerialization dataWithPropertyList:self format:NSPropertyListXMLFormat_v1_0 options:kNilOptions error:NULL];
if (xmlData) return xmlData.utf8String;
return nil;
}
- (id)randomObject {
if (self.count) {
return self[arc4random_uniform((u_int32_t)self.count)];
}
return nil;
}
- (id)objectOrNilAtIndex:(NSUInteger)index {
return index < self.count ? self[index] : nil;
}
- (NSString *)jsonStringEncoded {
if ([NSJSONSerialization isValidJSONObject:self]) {
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:0 error:&error];
NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
if (!error) return json;
}
return nil;
}
- (NSString *)jsonPrettyStringEncoded {
if ([NSJSONSerialization isValidJSONObject:self]) {
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
if (!error) return json;
}
return nil;
}
@end
@implementation NSMutableArray (YYAdd)
+ (NSMutableArray *)arrayWithPlistData:(NSData *)plist {
if (!plist) return nil;
NSMutableArray *array = [NSPropertyListSerialization propertyListWithData:plist options:NSPropertyListMutableContainersAndLeaves format:NULL error:NULL];
if ([array isKindOfClass:[NSMutableArray class]]) return array;
return nil;
}
+ (NSMutableArray *)arrayWithPlistString:(NSString *)plist {
if (!plist) return nil;
NSData *data = [plist dataUsingEncoding:NSUTF8StringEncoding];
return [self arrayWithPlistData:data];
}
- (void)removeFirstObject {
if (self.count) {
[self removeObjectAtIndex:0];
}
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
- (void)removeLastObject {
if (self.count) {
[self removeObjectAtIndex:self.count - 1];
}
}
#pragma clang diagnostic pop
- (id)popFirstObject {
id obj = nil;
if (self.count) {
obj = self.firstObject;
[self removeFirstObject];
}
return obj;
}
- (id)popLastObject {
id obj = nil;
if (self.count) {
obj = self.lastObject;
[self removeLastObject];
}
return obj;
}
- (void)appendObject:(id)anObject {
[self addObject:anObject];
}
- (void)prependObject:(id)anObject {
[self insertObject:anObject atIndex:0];
}
- (void)appendObjects:(NSArray *)objects {
if (!objects) return;
[self addObjectsFromArray:objects];
}
- (void)prependObjects:(NSArray *)objects {
if (!objects) return;
NSUInteger i = 0;
for (id obj in objects) {
[self insertObject:obj atIndex:i++];
}
}
- (void)insertObjects:(NSArray *)objects atIndex:(NSUInteger)index {
NSUInteger i = index;
for (id obj in objects) {
[self insertObject:obj atIndex:i++];
}
}
- (void)reverse {
NSUInteger count = self.count;
int mid = floor(count / 2.0);
for (NSUInteger i = 0; i < mid; i++) {
[self exchangeObjectAtIndex:i withObjectAtIndex:(count - (i + 1))];
}
}
- (void)shuffle {
for (NSUInteger i = self.count; i > 1; i--) {
[self exchangeObjectAtIndex:(i - 1)
withObjectAtIndex:arc4random_uniform((u_int32_t)i)];
}
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSArray+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,109
|
```objective-c
//
// NSNotificationCenter+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 13/8/24.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provide some method for `NSNotificationCenter`
to post notification in different thread.
*/
@interface NSNotificationCenter (YYAdd)
/**
Posts a given notification to the receiver on main thread.
If current thread is main thread, the notification is posted synchronously;
otherwise, is posted asynchronously.
@param notification The notification to post.
An exception is raised if notification is nil.
*/
- (void)postNotificationOnMainThread:(NSNotification *)notification;
/**
Posts a given notification to the receiver on main thread.
@param notification The notification to post.
An exception is raised if notification is nil.
@param wait A Boolean that specifies whether the current thread blocks
until after the specified notification is posted on the
receiver on the main thread. Specify YES to block this
thread; otherwise, specify NO to have this method return
immediately.
*/
- (void)postNotificationOnMainThread:(NSNotification *)notification
waitUntilDone:(BOOL)wait;
/**
Creates a notification with a given name and sender and posts it to the
receiver on main thread. If current thread is main thread, the notification
is posted synchronously; otherwise, is posted asynchronously.
@param name The name of the notification.
@param object The object posting the notification.
*/
- (void)postNotificationOnMainThreadWithName:(NSString *)name
object:(nullable id)object;
/**
Creates a notification with a given name and sender and posts it to the
receiver on main thread. If current thread is main thread, the notification
is posted synchronously; otherwise, is posted asynchronously.
@param name The name of the notification.
@param object The object posting the notification.
@param userInfo Information about the the notification. May be nil.
*/
- (void)postNotificationOnMainThreadWithName:(NSString *)name
object:(nullable id)object
userInfo:(nullable NSDictionary *)userInfo;
/**
Creates a notification with a given name and sender and posts it to the
receiver on main thread.
@param name The name of the notification.
@param object The object posting the notification.
@param userInfo Information about the the notification. May be nil.
@param wait A Boolean that specifies whether the current thread blocks
until after the specified notification is posted on the
receiver on the main thread. Specify YES to block this
thread; otherwise, specify NO to have this method return
immediately.
*/
- (void)postNotificationOnMainThreadWithName:(NSString *)name
object:(nullable id)object
userInfo:(nullable NSDictionary *)userInfo
waitUntilDone:(BOOL)wait;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSNotificationCenter+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 629
|
```objective-c
//
// NSString+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 13/4/3.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provide hash, encrypt, encode and some common method for 'NSString'.
*/
@interface NSString (YYAdd)
#pragma mark - Hash
///=============================================================================
/// @name Hash
///=============================================================================
/**
Returns a lowercase NSString for md2 hash.
*/
- (nullable NSString *)md2String;
/**
Returns a lowercase NSString for md4 hash.
*/
- (nullable NSString *)md4String;
/**
Returns a lowercase NSString for md5 hash.
*/
- (nullable NSString *)md5String;
/**
Returns a lowercase NSString for sha1 hash.
*/
- (nullable NSString *)sha1String;
/**
Returns a lowercase NSString for sha224 hash.
*/
- (nullable NSString *)sha224String;
/**
Returns a lowercase NSString for sha256 hash.
*/
- (nullable NSString *)sha256String;
/**
Returns a lowercase NSString for sha384 hash.
*/
- (nullable NSString *)sha384String;
/**
Returns a lowercase NSString for sha512 hash.
*/
- (nullable NSString *)sha512String;
/**
Returns a lowercase NSString for hmac using algorithm md5 with key.
@param key The hmac key.
*/
- (nullable NSString *)hmacMD5StringWithKey:(NSString *)key;
/**
Returns a lowercase NSString for hmac using algorithm sha1 with key.
@param key The hmac key.
*/
- (nullable NSString *)hmacSHA1StringWithKey:(NSString *)key;
/**
Returns a lowercase NSString for hmac using algorithm sha224 with key.
@param key The hmac key.
*/
- (nullable NSString *)hmacSHA224StringWithKey:(NSString *)key;
/**
Returns a lowercase NSString for hmac using algorithm sha256 with key.
@param key The hmac key.
*/
- (nullable NSString *)hmacSHA256StringWithKey:(NSString *)key;
/**
Returns a lowercase NSString for hmac using algorithm sha384 with key.
@param key The hmac key.
*/
- (nullable NSString *)hmacSHA384StringWithKey:(NSString *)key;
/**
Returns a lowercase NSString for hmac using algorithm sha512 with key.
@param key The hmac key.
*/
- (nullable NSString *)hmacSHA512StringWithKey:(NSString *)key;
/**
Returns a lowercase NSString for crc32 hash.
*/
- (nullable NSString *)crc32String;
#pragma mark - Encode and decode
///=============================================================================
/// @name Encode and decode
///=============================================================================
/**
Returns an NSString for base64 encoded.
*/
- (nullable NSString *)base64EncodedString;
/**
Returns an NSString from base64 encoded string.
@param base64Encoding The encoded string.
*/
+ (nullable NSString *)stringWithBase64EncodedString:(NSString *)base64EncodedString;
/**
URL encode a string in utf-8.
@return the encoded string.
*/
- (NSString *)stringByURLEncode;
/**
URL decode a string in utf-8.
@return the decoded string.
*/
- (NSString *)stringByURLDecode;
/**
Escape common HTML to Entity.
Example: "a<b" will be escape to "a<b".
*/
- (NSString *)stringByEscapingHTML;
#pragma mark - Drawing
///=============================================================================
/// @name Drawing
///=============================================================================
/**
Returns the size of the string if it were rendered with the specified constraints.
@param font The font to use for computing the string size.
@param size The maximum acceptable size for the string. This value is
used to calculate where line breaks and wrapping would occur.
@param lineBreakMode The line break options for computing the size of the string.
For a list of possible values, see NSLineBreakMode.
@return The width and height of the resulting string's bounding box.
These values may be rounded up to the nearest whole number.
*/
- (CGSize)sizeForFont:(UIFont *)font size:(CGSize)size mode:(NSLineBreakMode)lineBreakMode;
/**
Returns the width of the string if it were to be rendered with the specified
font on a single line.
@param font The font to use for computing the string width.
@return The width of the resulting string's bounding box. These values may be
rounded up to the nearest whole number.
*/
- (CGFloat)widthForFont:(UIFont *)font;
/**
Returns the height of the string if it were rendered with the specified constraints.
@param font The font to use for computing the string size.
@param width The maximum acceptable width for the string. This value is used
to calculate where line breaks and wrapping would occur.
@return The height of the resulting string's bounding box. These values
may be rounded up to the nearest whole number.
*/
- (CGFloat)heightForFont:(UIFont *)font width:(CGFloat)width;
#pragma mark - Regular Expression
///=============================================================================
/// @name Regular Expression
///=============================================================================
/**
Whether it can match the regular expression
@param regex The regular expression
@param options The matching options to report.
@return YES if can match the regex; otherwise, NO.
*/
- (BOOL)matchesRegex:(NSString *)regex options:(NSRegularExpressionOptions)options;
/**
Match the regular expression, and executes a given block using each object in the matches.
@param regex The regular expression
@param options The matching options to report.
@param block The block to apply to elements in the array of matches.
The block takes four arguments:
match: The match substring.
matchRange: The matching options.
stop: A reference to a Boolean value. The block can set the value
to YES to stop further processing of the array. The stop
argument is an out-only argument. You should only ever set
this Boolean to YES within the Block.
*/
- (void)enumerateRegexMatches:(NSString *)regex
options:(NSRegularExpressionOptions)options
usingBlock:(void (^)(NSString *match, NSRange matchRange, BOOL *stop))block;
/**
Returns a new string containing matching regular expressions replaced with the template string.
@param regex The regular expression
@param options The matching options to report.
@param replacement The substitution template used when replacing matching instances.
@return A string with matching regular expressions replaced by the template string.
*/
- (NSString *)stringByReplacingRegex:(NSString *)regex
options:(NSRegularExpressionOptions)options
withString:(NSString *)replacement;
#pragma mark - NSNumber Compatible
///=============================================================================
/// @name NSNumber Compatible
///=============================================================================
// Now you can use NSString as a NSNumber.
@property (readonly) char charValue;
@property (readonly) unsigned char unsignedCharValue;
@property (readonly) short shortValue;
@property (readonly) unsigned short unsignedShortValue;
@property (readonly) unsigned int unsignedIntValue;
@property (readonly) long longValue;
@property (readonly) unsigned long unsignedLongValue;
@property (readonly) unsigned long long unsignedLongLongValue;
@property (readonly) NSUInteger unsignedIntegerValue;
#pragma mark - Utilities
///=============================================================================
/// @name Utilities
///=============================================================================
/**
Returns a new UUID NSString
e.g. "D1178E50-2A4D-4F1F-9BD3-F6AAB00E06B1"
*/
+ (NSString *)stringWithUUID;
/**
Returns a string containing the characters in a given UTF32Char.
@param char32 A UTF-32 character.
@return A new string, or nil if the character is invalid.
*/
+ (nullable NSString *)stringWithUTF32Char:(UTF32Char)char32;
/**
Returns a string containing the characters in a given UTF32Char array.
@param char32 An array of UTF-32 character.
@param length The character count in array.
@return A new string, or nil if an error occurs.
*/
+ (nullable NSString *)stringWithUTF32Chars:(const UTF32Char *)char32 length:(NSUInteger)length;
/**
Enumerates the unicode characters (UTF-32) in the specified range of the string.
@param range The range within the string to enumerate substrings.
@param block The block executed for the enumeration. The block takes four arguments:
char32: The unicode character.
range: The range in receiver. If the range.length is 1, the character is in BMP;
otherwise (range.length is 2) the character is in none-BMP Plane and stored
by a surrogate pair in the receiver.
stop: A reference to a Boolean value that the block can use to stop the enumeration
by setting *stop = YES; it should not touch *stop otherwise.
*/
- (void)enumerateUTF32CharInRange:(NSRange)range usingBlock:(void (^)(UTF32Char char32, NSRange range, BOOL *stop))block;
/**
Trim blank characters (space and newline) in head and tail.
@return the trimmed string.
*/
- (NSString *)stringByTrim;
/**
Add scale modifier to the file name (without path extension),
From @"name" to @"name@2x".
e.g.
<table>
<tr><th>Before </th><th>After(scale:2)</th></tr>
<tr><td>"icon" </td><td>"icon@2x" </td></tr>
<tr><td>"icon " </td><td>"icon @2x" </td></tr>
<tr><td>"icon.top" </td><td>"icon.top@2x" </td></tr>
<tr><td>"/p/name" </td><td>"/p/name@2x" </td></tr>
<tr><td>"/path/" </td><td>"/path/" </td></tr>
</table>
@param scale Resource scale.
@return String by add scale modifier, or just return if it's not end with file name.
*/
- (NSString *)stringByAppendingNameScale:(CGFloat)scale;
/**
Add scale modifier to the file path (with path extension),
From @"name.png" to @"name@2x.png".
e.g.
<table>
<tr><th>Before </th><th>After(scale:2)</th></tr>
<tr><td>"icon.png" </td><td>"icon@2x.png" </td></tr>
<tr><td>"icon..png"</td><td>"icon.@2x.png"</td></tr>
<tr><td>"icon" </td><td>"icon@2x" </td></tr>
<tr><td>"icon " </td><td>"icon @2x" </td></tr>
<tr><td>"icon." </td><td>"icon.@2x" </td></tr>
<tr><td>"/p/name" </td><td>"/p/name@2x" </td></tr>
<tr><td>"/path/" </td><td>"/path/" </td></tr>
</table>
@param scale Resource scale.
@return String by add scale modifier, or just return if it's not end with file name.
*/
- (NSString *)stringByAppendingPathScale:(CGFloat)scale;
/**
Return the path scale.
e.g.
<table>
<tr><th>Path </th><th>Scale </th></tr>
<tr><td>"icon.png" </td><td>1 </td></tr>
<tr><td>"icon@2x.png" </td><td>2 </td></tr>
<tr><td>"icon@2.5x.png" </td><td>2.5 </td></tr>
<tr><td>"icon@2x" </td><td>1 </td></tr>
<tr><td>"icon@2x..png" </td><td>1 </td></tr>
<tr><td>"icon@2x.png/" </td><td>1 </td></tr>
</table>
*/
- (CGFloat)pathScale;
/**
nil, @"", @" ", @"\n" will Returns NO; otherwise Returns YES.
*/
- (BOOL)isNotBlank;
/**
Returns YES if the target string is contained within the receiver.
@param string A string to test the the receiver.
@discussion Apple has implemented this method in iOS8.
*/
- (BOOL)containsString:(NSString *)string;
/**
Returns YES if the target CharacterSet is contained within the receiver.
@param set A character set to test the the receiver.
*/
- (BOOL)containsCharacterSet:(NSCharacterSet *)set;
/**
Try to parse this string and returns an `NSNumber`.
@return Returns an `NSNumber` if parse succeed, or nil if an error occurs.
*/
- (nullable NSNumber *)numberValue;
/**
Returns an NSData using UTF-8 encoding.
*/
- (nullable NSData *)dataValue;
/**
Returns NSMakeRange(0, self.length).
*/
- (NSRange)rangeOfAll;
/**
Returns an NSDictionary/NSArray which is decoded from receiver.
Returns nil if an error occurs.
e.g. NSString: @"{"name":"a","count":2}" => NSDictionary: @[@"name":@"a",@"count":@2]
*/
- (nullable id)jsonValueDecoded;
/**
Create a string from the file in main bundle (similar to [UIImage imageNamed:]).
@param name The file name (in main bundle).
@return A new string create from the file in UTF-8 character encoding.
*/
+ (nullable NSString *)stringNamed:(NSString *)name;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSString+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 2,896
|
```objective-c
//
// NSDictionary+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 13/4/4.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "NSDictionary+YYAdd.h"
#import "NSString+YYAdd.h"
#import "NSData+YYAdd.h"
#import "YYKitMacro.h"
YYSYNTH_DUMMY_CLASS(NSDictionary_YYAdd)
@interface _YYXMLDictionaryParser : NSObject <NSXMLParserDelegate>
@end
@implementation _YYXMLDictionaryParser {
NSMutableDictionary *_root;
NSMutableArray *_stack;
NSMutableString *_text;
}
- (instancetype)initWithData:(NSData *)data {
self = super.init;
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
[parser setDelegate:self];
[parser parse];
return self;
}
- (instancetype)initWithString:(NSString *)xml {
NSData *data = [xml dataUsingEncoding:NSUTF8StringEncoding];
return [self initWithData:data];
}
- (NSDictionary *)result {
return _root;
}
#pragma mark - NSXMLParserDelegate
#define XMLText @"_text"
#define XMLName @"_name"
#define XMLPref @"_"
- (void)textEnd {
_text = _text.stringByTrim.mutableCopy;
if (_text.length) {
NSMutableDictionary *top = _stack.lastObject;
id existing = top[XMLText];
if ([existing isKindOfClass:[NSArray class]]) {
[existing addObject:_text];
} else if (existing) {
top[XMLText] = [@[existing, _text] mutableCopy];
} else {
top[XMLText] = _text;
}
}
_text = nil;
}
- (void)parser:(__unused NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(__unused NSString *)namespaceURI qualifiedName:(__unused NSString *)qName attributes:(NSDictionary *)attributeDict {
[self textEnd];
NSMutableDictionary *node = [NSMutableDictionary new];
if (!_root) node[XMLName] = elementName;
if (attributeDict.count) [node addEntriesFromDictionary:attributeDict];
if (_root) {
NSMutableDictionary *top = _stack.lastObject;
id existing = top[elementName];
if ([existing isKindOfClass:[NSArray class]]) {
[existing addObject:node];
} else if (existing) {
top[elementName] = [@[existing, node] mutableCopy];
} else {
top[elementName] = node;
}
[_stack addObject:node];
} else {
_root = node;
_stack = [NSMutableArray arrayWithObject:node];
}
}
- (void)parser:(__unused NSXMLParser *)parser didEndElement:(__unused NSString *)elementName namespaceURI:(__unused NSString *)namespaceURI qualifiedName:(__unused NSString *)qName {
[self textEnd];
NSMutableDictionary *top = _stack.lastObject;
[_stack removeLastObject];
NSMutableDictionary *left = top.mutableCopy;
[left removeObjectsForKeys:@[XMLText, XMLName]];
for (NSString *key in left.allKeys) {
[left removeObjectForKey:key];
if ([key hasPrefix:XMLPref]) {
left[[key substringFromIndex:XMLPref.length]] = top[key];
}
}
if (left.count) return;
NSMutableDictionary *children = top.mutableCopy;
[children removeObjectsForKeys:@[XMLText, XMLName]];
for (NSString *key in children.allKeys) {
if ([key hasPrefix:XMLPref]) {
[children removeObjectForKey:key];
}
}
if (children.count) return;
NSMutableDictionary *topNew = _stack.lastObject;
NSString *nodeName = top[XMLName];
if (!nodeName) {
for (NSString *name in topNew) {
id object = topNew[name];
if (object == top) {
nodeName = name; break;
} else if ([object isKindOfClass:[NSArray class]] && [object containsObject:top]) {
nodeName = name; break;
}
}
}
if (!nodeName) return;
id inner = top[XMLText];
if ([inner isKindOfClass:[NSArray class]]) {
inner = [inner componentsJoinedByString:@"\n"];
}
if (!inner) return;
id parent = topNew[nodeName];
if ([parent isKindOfClass:[NSArray class]]) {
NSArray *parentAsArray = parent;
parent[parentAsArray.count - 1] = inner;
} else {
topNew[nodeName] = inner;
}
}
- (void)parser:(__unused NSXMLParser *)parser foundCharacters:(NSString *)string {
if (_text) [_text appendString:string];
else _text = [NSMutableString stringWithString:string];
}
- (void)parser:(__unused NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock {
NSString *string = [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];
if (_text) [_text appendString:string];
else _text = [NSMutableString stringWithString:string];
}
#undef XMLText
#undef XMLName
#undef XMLPref
@end
@implementation NSDictionary (YYAdd)
+ (NSDictionary *)dictionaryWithPlistData:(NSData *)plist {
if (!plist) return nil;
NSDictionary *dictionary = [NSPropertyListSerialization propertyListWithData:plist options:NSPropertyListImmutable format:NULL error:NULL];
if ([dictionary isKindOfClass:[NSDictionary class]]) return dictionary;
return nil;
}
+ (NSDictionary *)dictionaryWithPlistString:(NSString *)plist {
if (!plist) return nil;
NSData *data = [plist dataUsingEncoding:NSUTF8StringEncoding];
return [self dictionaryWithPlistData:data];
}
- (NSData *)plistData {
return [NSPropertyListSerialization dataWithPropertyList:self format:NSPropertyListBinaryFormat_v1_0 options:kNilOptions error:NULL];
}
- (NSString *)plistString {
NSData *xmlData = [NSPropertyListSerialization dataWithPropertyList:self format:NSPropertyListXMLFormat_v1_0 options:kNilOptions error:NULL];
if (xmlData) return xmlData.utf8String;
return nil;
}
- (NSArray *)allKeysSorted {
return [[self allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
}
- (NSArray *)allValuesSortedByKeys {
NSArray *sortedKeys = [self allKeysSorted];
NSMutableArray *arr = [[NSMutableArray alloc] init];
for (id key in sortedKeys) {
[arr addObject:self[key]];
}
return [arr copy];
}
- (BOOL)containsObjectForKey:(id)key {
if (!key) return NO;
return self[key] != nil;
}
- (NSDictionary *)entriesForKeys:(NSArray *)keys {
NSMutableDictionary *dic = [NSMutableDictionary new];
for (id key in keys) {
id value = self[key];
if (value) dic[key] = value;
}
return [dic copy];
}
- (NSString *)jsonStringEncoded {
if ([NSJSONSerialization isValidJSONObject:self]) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:0 error:&error];
NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
if (!error) return json;
}
return nil;
}
- (NSString *)jsonPrettyStringEncoded {
if ([NSJSONSerialization isValidJSONObject:self]) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
if (!error) return json;
}
return nil;
}
+ (NSDictionary *)dictionaryWithXML:(id)xml {
_YYXMLDictionaryParser *parser = nil;
if ([xml isKindOfClass:[NSString class]]) {
parser = [[_YYXMLDictionaryParser alloc] initWithString:xml];
} else if ([xml isKindOfClass:[NSData class]]) {
parser = [[_YYXMLDictionaryParser alloc] initWithData:xml];
}
return [parser result];
}
/// Get a number value from 'id'.
static NSNumber *NSNumberFromID(id value) {
static NSCharacterSet *dot;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dot = [NSCharacterSet characterSetWithRange:NSMakeRange('.', 1)];
});
if (!value || value == [NSNull null]) return nil;
if ([value isKindOfClass:[NSNumber class]]) return value;
if ([value isKindOfClass:[NSString class]]) {
NSString *lower = ((NSString *)value).lowercaseString;
if ([lower isEqualToString:@"true"] || [lower isEqualToString:@"yes"]) return @(YES);
if ([lower isEqualToString:@"false"] || [lower isEqualToString:@"no"]) return @(NO);
if ([lower isEqualToString:@"nil"] || [lower isEqualToString:@"null"]) return nil;
if ([(NSString *)value rangeOfCharacterFromSet:dot].location != NSNotFound) {
return @(((NSString *)value).doubleValue);
} else {
return @(((NSString *)value).longLongValue);
}
}
return nil;
}
#define RETURN_VALUE(_type_) \
if (!key) return def; \
id value = self[key]; \
if (!value || value == [NSNull null]) return def; \
if ([value isKindOfClass:[NSNumber class]]) return ((NSNumber *)value)._type_; \
if ([value isKindOfClass:[NSString class]]) return NSNumberFromID(value)._type_; \
return def;
- (BOOL)boolValueForKey:(NSString *)key default:(BOOL)def {
RETURN_VALUE(boolValue);
}
- (char)charValueForKey:(NSString *)key default:(char)def {
RETURN_VALUE(charValue);
}
- (unsigned char)unsignedCharValueForKey:(NSString *)key default:(unsigned char)def {
RETURN_VALUE(unsignedCharValue);
}
- (short)shortValueForKey:(NSString *)key default:(short)def {
RETURN_VALUE(shortValue);
}
- (unsigned short)unsignedShortValueForKey:(NSString *)key default:(unsigned short)def {
RETURN_VALUE(unsignedShortValue);
}
- (int)intValueForKey:(NSString *)key default:(int)def {
RETURN_VALUE(intValue);
}
- (unsigned int)unsignedIntValueForKey:(NSString *)key default:(unsigned int)def {
RETURN_VALUE(unsignedIntValue);
}
- (long)longValueForKey:(NSString *)key default:(long)def {
RETURN_VALUE(longValue);
}
- (unsigned long)unsignedLongValueForKey:(NSString *)key default:(unsigned long)def {
RETURN_VALUE(unsignedLongValue);
}
- (long long)longLongValueForKey:(NSString *)key default:(long long)def {
RETURN_VALUE(longLongValue);
}
- (unsigned long long)unsignedLongLongValueForKey:(NSString *)key default:(unsigned long long)def {
RETURN_VALUE(unsignedLongLongValue);
}
- (float)floatValueForKey:(NSString *)key default:(float)def {
RETURN_VALUE(floatValue);
}
- (double)doubleValueForKey:(NSString *)key default:(double)def {
RETURN_VALUE(doubleValue);
}
- (NSInteger)integerValueForKey:(NSString *)key default:(NSInteger)def {
RETURN_VALUE(integerValue);
}
- (NSUInteger)unsignedIntegerValueForKey:(NSString *)key default:(NSUInteger)def {
RETURN_VALUE(unsignedIntegerValue);
}
- (NSNumber *)numberValueForKey:(NSString *)key default:(NSNumber *)def {
if (!key) return def;
id value = self[key];
if (!value || value == [NSNull null]) return def;
if ([value isKindOfClass:[NSNumber class]]) return value;
if ([value isKindOfClass:[NSString class]]) return NSNumberFromID(value);
return def;
}
- (NSString *)stringValueForKey:(NSString *)key default:(NSString *)def {
if (!key) return def;
id value = self[key];
if (!value || value == [NSNull null]) return def;
if ([value isKindOfClass:[NSString class]]) return value;
if ([value isKindOfClass:[NSNumber class]]) return ((NSNumber *)value).description;
return def;
}
@end
@implementation NSMutableDictionary (YYAdd)
+ (NSMutableDictionary *)dictionaryWithPlistData:(NSData *)plist {
if (!plist) return nil;
NSMutableDictionary *dictionary = [NSPropertyListSerialization propertyListWithData:plist options:NSPropertyListMutableContainersAndLeaves format:NULL error:NULL];
if ([dictionary isKindOfClass:[NSMutableDictionary class]]) return dictionary;
return nil;
}
+ (NSMutableDictionary *)dictionaryWithPlistString:(NSString *)plist {
if (!plist) return nil;
NSData *data = [plist dataUsingEncoding:NSUTF8StringEncoding];
return [self dictionaryWithPlistData:data];
}
- (id)popObjectForKey:(id)aKey {
if (!aKey) return nil;
id value = self[aKey];
[self removeObjectForKey:aKey];
return value;
}
- (NSDictionary *)popEntriesForKeys:(NSArray *)keys {
NSMutableDictionary *dic = [NSMutableDictionary new];
for (id key in keys) {
id value = self[key];
if (value) {
[self removeObjectForKey:key];
dic[key] = value;
}
}
return [dic copy];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSDictionary+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 2,841
|
```objective-c
//
// NSObject+YYAddForARC.h
// YYKit <path_to_url
//
// Created by ibireme on 13/12/15.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <Foundation/Foundation.h>
/**
Debug method for NSObject when using ARC.
*/
@interface NSObject (YYAddForARC)
/// Same as `retain`
- (instancetype)arcDebugRetain;
/// Same as `release`
- (oneway void)arcDebugRelease;
/// Same as `autorelease`
- (instancetype)arcDebugAutorelease;
/// Same as `retainCount`
- (NSUInteger)arcDebugRetainCount;
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSObject+YYAddForARC.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 157
|
```objective-c
//
// NSBundle+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 14/10/20.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provides extensions for `NSBundle` to get resource by @2x or @3x...
Example: ico.png, ico@2x.png, ico@3x.png. Call scaledResource:@"ico" ofType:@"png"
on iPhone6 will return "ico@2x.png"'s path.
*/
@interface NSBundle (YYAdd)
/**
An array of NSNumber objects, shows the best order for path scale search.
e.g. iPhone3GS:@[@1,@2,@3] iPhone5:@[@2,@3,@1] iPhone6 Plus:@[@3,@2,@1]
*/
+ (NSArray<NSNumber *> *)preferredScales;
/**
Returns the full pathname for the resource file identified by the specified
name and extension and residing in a given bundle directory. It first search
the file with current screen's scale (such as @2x), then search from higher
scale to lower scale.
@param name The name of a resource file contained in the directory
specified by bundlePath.
@param ext If extension is an empty string or nil, the extension is
assumed not to exist and the file is the first file encountered that exactly matches name.
@param bundlePath The path of a top-level bundle directory. This must be a
valid path. For example, to specify the bundle directory for a Mac app, you
might specify the path /Applications/MyApp.app.
@return The full pathname for the resource file or nil if the file could not be
located. This method also returns nil if the bundle specified by the bundlePath
parameter does not exist or is not a readable directory.
*/
+ (nullable NSString *)pathForScaledResource:(NSString *)name
ofType:(nullable NSString *)ext
inDirectory:(NSString *)bundlePath;
/**
Returns the full pathname for the resource identified by the specified name and
file extension. It first search the file with current screen's scale (such as @2x),
then search from higher scale to lower scale.
@param name The name of the resource file. If name is an empty string or
nil, returns the first file encountered of the supplied type.
@param ext If extension is an empty string or nil, the extension is
assumed not to exist and the file is the first file encountered that exactly matches name.
@return The full pathname for the resource file or nil if the file could not be located.
*/
- (nullable NSString *)pathForScaledResource:(NSString *)name ofType:(nullable NSString *)ext;
/**
Returns the full pathname for the resource identified by the specified name and
file extension and located in the specified bundle subdirectory. It first search
the file with current screen's scale (such as @2x), then search from higher
scale to lower scale.
@param name The name of the resource file.
@param ext If extension is an empty string or nil, all the files in
subpath and its subdirectories are returned. If an extension is provided the
subdirectories are not searched.
@param subpath The name of the bundle subdirectory. Can be nil.
@return The full pathname for the resource file or nil if the file could not be located.
*/
- (nullable NSString *)pathForScaledResource:(NSString *)name
ofType:(nullable NSString *)ext
inDirectory:(nullable NSString *)subpath;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSBundle+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 786
|
```objective-c
//
// NSObject+YYAddForKVO.h
// YYKit <path_to_url
//
// Created by ibireme on 14/10/15.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
Observer with block (KVO).
*/
@interface NSObject (YYAddForKVO)
/**
Registers a block to receive KVO notifications for the specified key-path
relative to the receiver.
@discussion The block and block captured objects are retained. Call
`removeObserverBlocksForKeyPath:` or `removeObserverBlocks` to release.
@param keyPath The key path, relative to the receiver, of the property to
observe. This value must not be nil.
@param block The block to register for KVO notifications.
*/
- (void)addObserverBlockForKeyPath:(NSString*)keyPath block:(void (^)(id _Nonnull obj, _Nullable id oldVal, _Nullable id newVal))block;
/**
Stops all blocks (associated by `addObserverBlockForKeyPath:block:`) from
receiving change notifications for the property specified by a given key-path
relative to the receiver, and release these blocks.
@param keyPath A key-path, relative to the receiver, for which blocks is
registered to receive KVO change notifications.
*/
- (void)removeObserverBlocksForKeyPath:(NSString*)keyPath;
/**
Stops all blocks (associated by `addObserverBlockForKeyPath:block:`) from
receiving change notifications, and release these blocks.
*/
- (void)removeObserverBlocks;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSObject+YYAddForKVO.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 354
|
```objective-c
//
// NSTimer+YYAdd.m
// YYKit <path_to_url
//
// Created by ibireme on 14/15/11.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "NSTimer+YYAdd.h"
#import "YYKitMacro.h"
YYSYNTH_DUMMY_CLASS(NSTimer_YYAdd)
@implementation NSTimer (YYAdd)
+ (void)_yy_ExecBlock:(NSTimer *)timer {
if ([timer userInfo]) {
void (^block)(NSTimer *timer) = (void (^)(NSTimer *timer))[timer userInfo];
block(timer);
}
}
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds block:(void (^)(NSTimer *timer))block repeats:(BOOL)repeats {
return [NSTimer scheduledTimerWithTimeInterval:seconds target:self selector:@selector(_yy_ExecBlock:) userInfo:[block copy] repeats:repeats];
}
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds block:(void (^)(NSTimer *timer))block repeats:(BOOL)repeats {
return [NSTimer timerWithTimeInterval:seconds target:self selector:@selector(_yy_ExecBlock:) userInfo:[block copy] repeats:repeats];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSTimer+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 282
|
```objective-c
//
// NSObject+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 14/10/8.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
Common tasks for NSObject.
*/
@interface NSObject (YYAdd)
#pragma mark - Sending messages with variable parameters
///=============================================================================
/// @name Sending messages with variable parameters
///=============================================================================
/**
Sends a specified message to the receiver and returns the result of the message.
@param sel A selector identifying the message to send. If the selector is
NULL or unrecognized, an NSInvalidArgumentException is raised.
@param ... Variable parameter list. Parameters type must correspond to the
selector's method declaration, or unexpected results may occur.
It doesn't support union or struct which is larger than 256 bytes.
@return An object that is the result of the message.
@discussion The selector's return value will be wrap as NSNumber or NSValue
if the selector's `return type` is not object. It always returns nil
if the selector's `return type` is void.
Sample Code:
// no variable args
[view performSelectorWithArgs:@selector(removeFromSuperView)];
// variable arg is not object
[view performSelectorWithArgs:@selector(setCenter:), CGPointMake(0, 0)];
// perform and return object
UIImage *image = [UIImage.class performSelectorWithArgs:@selector(imageWithData:scale:), data, 2.0];
// perform and return wrapped number
NSNumber *lengthValue = [@"hello" performSelectorWithArgs:@selector(length)];
NSUInteger length = lengthValue.unsignedIntegerValue;
// perform and return wrapped struct
NSValue *frameValue = [view performSelectorWithArgs:@selector(frame)];
CGRect frame = frameValue.CGRectValue;
*/
- (nullable id)performSelectorWithArgs:(SEL)sel, ...;
/**
Invokes a method of the receiver on the current thread using the default mode after a delay.
@warning It can't cancelled by previous request.
@param sel A selector identifying the message to send. If the selector is
NULL or unrecognized, an NSInvalidArgumentException is raised immediately.
@param delay The minimum time before which the message is sent. Specifying
a delay of 0 does not necessarily cause the selector to be
performed immediately. The selector is still queued on the
thread's run loop and performed as soon as possible.
@param ... Variable parameter list. Parameters type must correspond to the
selector's method declaration, or unexpected results may occur.
It doesn't support union or struct which is larger than 256 bytes.
Sample Code:
// no variable args
[view performSelectorWithArgs:@selector(removeFromSuperView) afterDelay:2.0];
// variable arg is not object
[view performSelectorWithArgs:@selector(setCenter:), afterDelay:0, CGPointMake(0, 0)];
*/
- (void)performSelectorWithArgs:(SEL)sel afterDelay:(NSTimeInterval)delay, ...;
/**
Invokes a method of the receiver on the main thread using the default mode.
@param sel A selector identifying the message to send. If the selector is
NULL or unrecognized, an NSInvalidArgumentException is raised.
@param wait A Boolean that specifies whether the current thread blocks until
after the specified selector is performed on the receiver on the
specified thread. Specify YES to block this thread; otherwise,
specify NO to have this method return immediately.
@param ... Variable parameter list. Parameters type must correspond to the
selector's method declaration, or unexpected results may occur.
It doesn't support union or struct which is larger than 256 bytes.
@return While @a wait is YES, it returns object that is the result of
the message. Otherwise return nil;
@discussion The selector's return value will be wrap as NSNumber or NSValue
if the selector's `return type` is not object. It always returns nil
if the selector's `return type` is void, or @a wait is YES.
Sample Code:
// no variable args
[view performSelectorWithArgsOnMainThread:@selector(removeFromSuperView), waitUntilDone:NO];
// variable arg is not object
[view performSelectorWithArgsOnMainThread:@selector(setCenter:), waitUntilDone:NO, CGPointMake(0, 0)];
*/
- (nullable id)performSelectorWithArgsOnMainThread:(SEL)sel waitUntilDone:(BOOL)wait, ...;
/**
Invokes a method of the receiver on the specified thread using the default mode.
@param sel A selector identifying the message to send. If the selector is
NULL or unrecognized, an NSInvalidArgumentException is raised.
@param thread The thread on which to execute aSelector.
@param wait A Boolean that specifies whether the current thread blocks until
after the specified selector is performed on the receiver on the
specified thread. Specify YES to block this thread; otherwise,
specify NO to have this method return immediately.
@param ... Variable parameter list. Parameters type must correspond to the
selector's method declaration, or unexpected results may occur.
It doesn't support union or struct which is larger than 256 bytes.
@return While @a wait is YES, it returns object that is the result of
the message. Otherwise return nil;
@discussion The selector's return value will be wrap as NSNumber or NSValue
if the selector's `return type` is not object. It always returns nil
if the selector's `return type` is void, or @a wait is YES.
Sample Code:
[view performSelectorWithArgs:@selector(removeFromSuperView) onThread:mainThread waitUntilDone:NO];
[array performSelectorWithArgs:@selector(sortUsingComparator:)
onThread:backgroundThread
waitUntilDone:NO, ^NSComparisonResult(NSNumber *num1, NSNumber *num2) {
return [num2 compare:num2];
}];
*/
- (nullable id)performSelectorWithArgs:(SEL)sel onThread:(NSThread *)thread waitUntilDone:(BOOL)wait, ...;
/**
Invokes a method of the receiver on a new background thread.
@param sel A selector identifying the message to send. If the selector is
NULL or unrecognized, an NSInvalidArgumentException is raised.
@param ... Variable parameter list. Parameters type must correspond to the
selector's method declaration, or unexpected results may occur.
It doesn't support union or struct which is larger than 256 bytes.
@discussion This method creates a new thread in your application, putting
your application into multithreaded mode if it was not already.
The method represented by sel must set up the thread environment
just as you would for any other new thread in your program.
Sample Code:
[array performSelectorWithArgsInBackground:@selector(sortUsingComparator:),
^NSComparisonResult(NSNumber *num1, NSNumber *num2) {
return [num2 compare:num2];
}];
*/
- (void)performSelectorWithArgsInBackground:(SEL)sel, ...;
/**
Invokes a method of the receiver on the current thread after a delay.
@warning arc-performSelector-leaks
@param sel A selector that identifies the method to invoke. The method should
not have a significant return value and should take no argument.
If the selector is NULL or unrecognized,
an NSInvalidArgumentException is raised after the delay.
@param delay The minimum time before which the message is sent. Specifying a
delay of 0 does not necessarily cause the selector to be performed
immediately. The selector is still queued on the thread's run loop
and performed as soon as possible.
@discussion This method sets up a timer to perform the aSelector message on
the current thread's run loop. The timer is configured to run in
the default mode (NSDefaultRunLoopMode). When the timer fires, the
thread attempts to dequeue the message from the run loop and
perform the selector. It succeeds if the run loop is running and
in the default mode; otherwise, the timer waits until the run loop
is in the default mode.
*/
- (void)performSelector:(SEL)sel afterDelay:(NSTimeInterval)delay;
#pragma mark - Swap method (Swizzling)
///=============================================================================
/// @name Swap method (Swizzling)
///=============================================================================
/**
Swap two instance method's implementation in one class. Dangerous, be careful.
@param originalSel Selector 1.
@param newSel Selector 2.
@return YES if swizzling succeed; otherwise, NO.
*/
+ (BOOL)swizzleInstanceMethod:(SEL)originalSel with:(SEL)newSel;
/**
Swap two class method's implementation in one class. Dangerous, be careful.
@param originalSel Selector 1.
@param newSel Selector 2.
@return YES if swizzling succeed; otherwise, NO.
*/
+ (BOOL)swizzleClassMethod:(SEL)originalSel with:(SEL)newSel;
#pragma mark - Associate value
///=============================================================================
/// @name Associate value
///=============================================================================
/**
Associate one object to `self`, as if it was a strong property (strong, nonatomic).
@param value The object to associate.
@param key The pointer to get value from `self`.
*/
- (void)setAssociateValue:(nullable id)value withKey:(void *)key;
/**
Associate one object to `self`, as if it was a weak property (week, nonatomic).
@param value The object to associate.
@param key The pointer to get value from `self`.
*/
- (void)setAssociateWeakValue:(nullable id)value withKey:(void *)key;
/**
Get the associated value from `self`.
@param key The pointer to get value from `self`.
*/
- (nullable id)getAssociatedValueForKey:(void *)key;
/**
Remove all associated values.
*/
- (void)removeAssociatedValues;
#pragma mark - Others
///=============================================================================
/// @name Others
///=============================================================================
/**
Returns the class name in NSString.
*/
+ (NSString *)className;
/**
Returns the class name in NSString.
@discussion Apple has implemented this method in NSObject(NSLayoutConstraintCallsThis),
but did not make it public.
*/
- (NSString *)className;
/**
Returns a copy of the instance with `NSKeyedArchiver` and ``NSKeyedUnarchiver``.
Returns nil if an error occurs.
*/
- (nullable id)deepCopy;
/**
Returns a copy of the instance use archiver and unarchiver.
Returns nil if an error occurs.
@param archiver NSKeyedArchiver class or any class inherited.
@param unarchiver NSKeyedUnarchiver clsas or any class inherited.
*/
- (nullable id)deepCopyWithArchiver:(Class)archiver unarchiver:(Class)unarchiver;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSObject+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 2,388
|
```objective-c
//
// NSTimer+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 14/15/11.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provides extensions for `NSTimer`.
*/
@interface NSTimer (YYAdd)
/**
Creates and returns a new NSTimer object and schedules it on the current run
loop in the default mode.
@discussion After seconds seconds have elapsed, the timer fires,
sending the message aSelector to target.
@param seconds The number of seconds between firings of the timer. If seconds
is less than or equal to 0.0, this method chooses the
nonnegative value of 0.1 milliseconds instead.
@param block The block to invoke when the timer fires. The timer maintains
a strong reference to the block until it (the timer) is invalidated.
@param repeats If YES, the timer will repeatedly reschedule itself until
invalidated. If NO, the timer will be invalidated after it fires.
@return A new NSTimer object, configured according to the specified parameters.
*/
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds block:(void (^)(NSTimer *timer))block repeats:(BOOL)repeats;
/**
Creates and returns a new NSTimer object initialized with the specified block.
@discussion You must add the new timer to a run loop, using addTimer:forMode:.
Then, after seconds have elapsed, the timer fires, invoking
block. (If the timer is configured to repeat, there is no need
to subsequently re-add the timer to the run loop.)
@param seconds The number of seconds between firings of the timer. If seconds
is less than or equal to 0.0, this method chooses the
nonnegative value of 0.1 milliseconds instead.
@param block The block to invoke when the timer fires. The timer instructs
the block to maintain a strong reference to its arguments.
@param repeats If YES, the timer will repeatedly reschedule itself until
invalidated. If NO, the timer will be invalidated after it fires.
@return A new NSTimer object, configured according to the specified parameters.
*/
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds block:(void (^)(NSTimer *timer))block repeats:(BOOL)repeats;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSTimer+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 549
|
```objective-c
//
// NSDate+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 13/4/11.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provides extensions for `NSDate`.
*/
@interface NSDate (YYAdd)
#pragma mark - Component Properties
///=============================================================================
/// @name Component Properties
///=============================================================================
@property (nonatomic, readonly) NSInteger year; ///< Year component
@property (nonatomic, readonly) NSInteger month; ///< Month component (1~12)
@property (nonatomic, readonly) NSInteger day; ///< Day component (1~31)
@property (nonatomic, readonly) NSInteger hour; ///< Hour component (0~23)
@property (nonatomic, readonly) NSInteger minute; ///< Minute component (0~59)
@property (nonatomic, readonly) NSInteger second; ///< Second component (0~59)
@property (nonatomic, readonly) NSInteger nanosecond; ///< Nanosecond component
@property (nonatomic, readonly) NSInteger weekday; ///< Weekday component (1~7, first day is based on user setting)
@property (nonatomic, readonly) NSInteger weekdayOrdinal; ///< WeekdayOrdinal component
@property (nonatomic, readonly) NSInteger weekOfMonth; ///< WeekOfMonth component (1~5)
@property (nonatomic, readonly) NSInteger weekOfYear; ///< WeekOfYear component (1~53)
@property (nonatomic, readonly) NSInteger yearForWeekOfYear; ///< YearForWeekOfYear component
@property (nonatomic, readonly) NSInteger quarter; ///< Quarter component
@property (nonatomic, readonly) BOOL isLeapMonth; ///< whether the month is leap month
@property (nonatomic, readonly) BOOL isLeapYear; ///< whether the year is leap year
@property (nonatomic, readonly) BOOL isToday; ///< whether date is today (based on current locale)
@property (nonatomic, readonly) BOOL isYesterday; ///< whether date is yesterday (based on current locale)
#pragma mark - Date modify
///=============================================================================
/// @name Date modify
///=============================================================================
/**
Returns a date representing the receiver date shifted later by the provided number of years.
@param years Number of years to add.
@return Date modified by the number of desired years.
*/
- (nullable NSDate *)dateByAddingYears:(NSInteger)years;
/**
Returns a date representing the receiver date shifted later by the provided number of months.
@param months Number of months to add.
@return Date modified by the number of desired months.
*/
- (nullable NSDate *)dateByAddingMonths:(NSInteger)months;
/**
Returns a date representing the receiver date shifted later by the provided number of weeks.
@param weeks Number of weeks to add.
@return Date modified by the number of desired weeks.
*/
- (nullable NSDate *)dateByAddingWeeks:(NSInteger)weeks;
/**
Returns a date representing the receiver date shifted later by the provided number of days.
@param days Number of days to add.
@return Date modified by the number of desired days.
*/
- (nullable NSDate *)dateByAddingDays:(NSInteger)days;
/**
Returns a date representing the receiver date shifted later by the provided number of hours.
@param hours Number of hours to add.
@return Date modified by the number of desired hours.
*/
- (nullable NSDate *)dateByAddingHours:(NSInteger)hours;
/**
Returns a date representing the receiver date shifted later by the provided number of minutes.
@param minutes Number of minutes to add.
@return Date modified by the number of desired minutes.
*/
- (nullable NSDate *)dateByAddingMinutes:(NSInteger)minutes;
/**
Returns a date representing the receiver date shifted later by the provided number of seconds.
@param seconds Number of seconds to add.
@return Date modified by the number of desired seconds.
*/
- (nullable NSDate *)dateByAddingSeconds:(NSInteger)seconds;
#pragma mark - Date Format
///=============================================================================
/// @name Date Format
///=============================================================================
/**
Returns a formatted string representing this date.
see path_to_url#Date_Format_Patterns
for format description.
@param format String representing the desired date format.
e.g. @"yyyy-MM-dd HH:mm:ss"
@return NSString representing the formatted date string.
*/
- (nullable NSString *)stringWithFormat:(NSString *)format;
/**
Returns a formatted string representing this date.
see path_to_url#Date_Format_Patterns
for format description.
@param format String representing the desired date format.
e.g. @"yyyy-MM-dd HH:mm:ss"
@param timeZone Desired time zone.
@param locale Desired locale.
@return NSString representing the formatted date string.
*/
- (nullable NSString *)stringWithFormat:(NSString *)format
timeZone:(nullable NSTimeZone *)timeZone
locale:(nullable NSLocale *)locale;
/**
Returns a string representing this date in ISO8601 format.
e.g. "2010-07-09T16:13:30+12:00"
@return NSString representing the formatted date string in ISO8601.
*/
- (nullable NSString *)stringWithISOFormat;
/**
Returns a date parsed from given string interpreted using the format.
@param dateString The string to parse.
@param format The string's date format.
@return A date representation of string interpreted using the format.
If can not parse the string, returns nil.
*/
+ (nullable NSDate *)dateWithString:(NSString *)dateString format:(NSString *)format;
/**
Returns a date parsed from given string interpreted using the format.
@param dateString The string to parse.
@param format The string's date format.
@param timeZone The time zone, can be nil.
@param locale The locale, can be nil.
@return A date representation of string interpreted using the format.
If can not parse the string, returns nil.
*/
+ (nullable NSDate *)dateWithString:(NSString *)dateString
format:(NSString *)format
timeZone:(nullable NSTimeZone *)timeZone
locale:(nullable NSLocale *)locale;
/**
Returns a date parsed from given string interpreted using the ISO8601 format.
@param dateString The date string in ISO8601 format. e.g. "2010-07-09T16:13:30+12:00"
@return A date representation of string interpreted using the format.
If can not parse the string, returns nil.
*/
+ (nullable NSDate *)dateWithISOFormatString:(NSString *)dateString;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSDate+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,362
|
```objective-c
//
// NSThread+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 15/7/3.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "NSThread+YYAdd.h"
#import <CoreFoundation/CoreFoundation.h>
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
@interface NSThread_YYAdd : NSObject
@end
@implementation NSThread_YYAdd
@end
#if __has_feature(objc_arc)
#error This file must be compiled without ARC. Specify the -fno-objc-arc flag to this file.
#endif
static NSString *const YYNSThreadAutoleasePoolKey = @"YYNSThreadAutoleasePoolKey";
static NSString *const YYNSThreadAutoleasePoolStackKey = @"YYNSThreadAutoleasePoolStackKey";
static const void *PoolStackRetainCallBack(CFAllocatorRef allocator, const void *value) {
return value;
}
static void PoolStackReleaseCallBack(CFAllocatorRef allocator, const void *value) {
CFRelease((CFTypeRef)value);
}
static inline void YYAutoreleasePoolPush() {
NSMutableDictionary *dic = [NSThread currentThread].threadDictionary;
NSMutableArray *poolStack = dic[YYNSThreadAutoleasePoolStackKey];
if (!poolStack) {
/*
do not retain pool on push,
but release on pop to avoid memory analyze warning
*/
CFArrayCallBacks callbacks = {0};
callbacks.retain = PoolStackRetainCallBack;
callbacks.release = PoolStackReleaseCallBack;
poolStack = (id)CFArrayCreateMutable(CFAllocatorGetDefault(), 0, &callbacks);
dic[YYNSThreadAutoleasePoolStackKey] = poolStack;
CFRelease(poolStack);
}
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; //< create
[poolStack addObject:pool]; // push
}
static inline void YYAutoreleasePoolPop() {
NSMutableDictionary *dic = [NSThread currentThread].threadDictionary;
NSMutableArray *poolStack = dic[YYNSThreadAutoleasePoolStackKey];
[poolStack removeLastObject]; // pop
}
static void YYRunLoopAutoreleasePoolObserverCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) {
switch (activity) {
case kCFRunLoopEntry: {
YYAutoreleasePoolPush();
} break;
case kCFRunLoopBeforeWaiting: {
YYAutoreleasePoolPop();
YYAutoreleasePoolPush();
} break;
case kCFRunLoopExit: {
YYAutoreleasePoolPop();
} break;
default: break;
}
}
static void YYRunloopAutoreleasePoolSetup() {
CFRunLoopRef runloop = CFRunLoopGetCurrent();
CFRunLoopObserverRef pushObserver;
pushObserver = CFRunLoopObserverCreate(CFAllocatorGetDefault(), kCFRunLoopEntry,
true, // repeat
-0x7FFFFFFF, // before other observers
YYRunLoopAutoreleasePoolObserverCallBack, NULL);
CFRunLoopAddObserver(runloop, pushObserver, kCFRunLoopCommonModes);
CFRelease(pushObserver);
CFRunLoopObserverRef popObserver;
popObserver = CFRunLoopObserverCreate(CFAllocatorGetDefault(), kCFRunLoopBeforeWaiting | kCFRunLoopExit,
true, // repeat
0x7FFFFFFF, // after other observers
YYRunLoopAutoreleasePoolObserverCallBack, NULL);
CFRunLoopAddObserver(runloop, popObserver, kCFRunLoopCommonModes);
CFRelease(popObserver);
}
@implementation NSThread (YYAdd)
+ (void)addAutoreleasePoolToCurrentRunloop {
if ([NSThread isMainThread]) return; // The main thread already has autorelease pool.
NSThread *thread = [self currentThread];
if (!thread) return;
if (thread.threadDictionary[YYNSThreadAutoleasePoolKey]) return; // already added
YYRunloopAutoreleasePoolSetup();
thread.threadDictionary[YYNSThreadAutoleasePoolKey] = YYNSThreadAutoleasePoolKey; // mark the state
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSThread+YYAdd.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 909
|
```objective-c
//
// NSThread+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 15/7/3.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <Foundation/Foundation.h>
@interface NSThread (YYAdd)
/**
Add an autorelease pool to current runloop for current thread.
@discussion If you create your own thread (NSThread/pthread), and you use
runloop to manage your task, you may use this method to add an autorelease pool
to the runloop. Its behavior is the same as the main thread's autorelease pool.
*/
+ (void)addAutoreleasePoolToCurrentRunloop;
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSThread+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 164
|
```objective-c
//
// NSObject+YYAddForARC.m
// YYKit <path_to_url
//
// Created by ibireme on 13/12/15.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import "NSObject+YYAddForARC.h"
@interface NSObject_YYAddForARC : NSObject @end
@implementation NSObject_YYAddForARC @end
#if __has_feature(objc_arc)
#error This file must be compiled without ARC. Specify the -fno-objc-arc flag to this file.
#endif
@implementation NSObject (YYAddForARC)
- (instancetype)arcDebugRetain {
return [self retain];
}
- (oneway void)arcDebugRelease {
[self release];
}
- (instancetype)arcDebugAutorelease {
return [self autorelease];
}
- (NSUInteger)arcDebugRetainCount {
return [self retainCount];
}
@end
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSObject+YYAddForARC.m
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 209
|
```objective-c
//
// NSArray+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 13/4/4.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provide some some common method for `NSArray`.
*/
@interface NSArray (YYAdd)
/**
Creates and returns an array from a specified property list data.
@param plist A property list data whose root object is an array.
@return A new array created from the binary plist data, or nil if an error occurs.
*/
+ (nullable NSArray *)arrayWithPlistData:(NSData *)plist;
/**
Creates and returns an array from a specified property list xml string.
@param plist A property list xml string whose root object is an array.
@return A new array created from the plist string, or nil if an error occurs.
*/
+ (nullable NSArray *)arrayWithPlistString:(NSString *)plist;
/**
Serialize the array to a binary property list data.
@return A binary plist data, or nil if an error occurs.
*/
- (nullable NSData *)plistData;
/**
Serialize the array to a xml property list string.
@return A plist xml string, or nil if an error occurs.
*/
- (nullable NSString *)plistString;
/**
Returns the object located at a random index.
@return The object in the array with a random index value.
If the array is empty, returns nil.
*/
- (nullable id)randomObject;
/**
Returns the object located at index, or return nil when out of bounds.
It's similar to `objectAtIndex:`, but it never throw exception.
@param index The object located at index.
*/
- (nullable id)objectOrNilAtIndex:(NSUInteger)index;
/**
Convert object to json string. return nil if an error occurs.
NSString/NSNumber/NSDictionary/NSArray
*/
- (nullable NSString *)jsonStringEncoded;
/**
Convert object to json string formatted. return nil if an error occurs.
*/
- (nullable NSString *)jsonPrettyStringEncoded;
@end
/**
Provide some some common method for `NSMutableArray`.
*/
@interface NSMutableArray (YYAdd)
/**
Creates and returns an array from a specified property list data.
@param plist A property list data whose root object is an array.
@return A new array created from the binary plist data, or nil if an error occurs.
*/
+ (nullable NSMutableArray *)arrayWithPlistData:(NSData *)plist;
/**
Creates and returns an array from a specified property list xml string.
@param plist A property list xml string whose root object is an array.
@return A new array created from the plist string, or nil if an error occurs.
*/
+ (nullable NSMutableArray *)arrayWithPlistString:(NSString *)plist;
/**
Removes the object with the lowest-valued index in the array.
If the array is empty, this method has no effect.
@discussion Apple has implemented this method, but did not make it public.
Override for safe.
*/
- (void)removeFirstObject;
/**
Removes the object with the highest-valued index in the array.
If the array is empty, this method has no effect.
@discussion Apple's implementation said it raises an NSRangeException if the
array is empty, but in fact nothing will happen. Override for safe.
*/
- (void)removeLastObject;
/**
Removes and returns the object with the lowest-valued index in the array.
If the array is empty, it just returns nil.
@return The first object, or nil.
*/
- (nullable id)popFirstObject;
/**
Removes and returns the object with the highest-valued index in the array.
If the array is empty, it just returns nil.
@return The first object, or nil.
*/
- (nullable id)popLastObject;
/**
Inserts a given object at the end of the array.
@param anObject The object to add to the end of the array's content.
This value must not be nil. Raises an NSInvalidArgumentException if anObject is nil.
*/
- (void)appendObject:(id)anObject;
/**
Inserts a given object at the beginning of the array.
@param anObject The object to add to the end of the array's content.
This value must not be nil. Raises an NSInvalidArgumentException if anObject is nil.
*/
- (void)prependObject:(id)anObject;
/**
Adds the objects contained in another given array to the end of the receiving
array's content.
@param objects An array of objects to add to the end of the receiving array's
content. If the objects is empty or nil, this method has no effect.
*/
- (void)appendObjects:(NSArray *)objects;
/**
Adds the objects contained in another given array to the beginnin of the receiving
array's content.
@param objects An array of objects to add to the beginning of the receiving array's
content. If the objects is empty or nil, this method has no effect.
*/
- (void)prependObjects:(NSArray *)objects;
/**
Adds the objects contained in another given array at the index of the receiving
array's content.
@param objects An array of objects to add to the receiving array's
content. If the objects is empty or nil, this method has no effect.
@param index The index in the array at which to insert objects. This value must
not be greater than the count of elements in the array. Raises an
NSRangeException if index is greater than the number of elements in the array.
*/
- (void)insertObjects:(NSArray *)objects atIndex:(NSUInteger)index;
/**
Reverse the index of object in this array.
Example: Before @[ @1, @2, @3 ], After @[ @3, @2, @1 ].
*/
- (void)reverse;
/**
Sort the object in this array randomly.
*/
- (void)shuffle;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSArray+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,245
|
```objective-c
//
// NSData+YYAdd.h
// YYKit <path_to_url
//
// Created by ibireme on 13/4/4.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
Provide hash, encrypt, encode and some common method for `NSData`.
*/
@interface NSData (YYAdd)
#pragma mark - Hash
///=============================================================================
/// @name Hash
///=============================================================================
/**
Returns a lowercase NSString for md2 hash.
*/
- (NSString *)md2String;
/**
Returns an NSData for md2 hash.
*/
- (NSData *)md2Data;
/**
Returns a lowercase NSString for md4 hash.
*/
- (NSString *)md4String;
/**
Returns an NSData for md4 hash.
*/
- (NSData *)md4Data;
/**
Returns a lowercase NSString for md5 hash.
*/
- (NSString *)md5String;
/**
Returns an NSData for md5 hash.
*/
- (NSData *)md5Data;
/**
Returns a lowercase NSString for sha1 hash.
*/
- (NSString *)sha1String;
/**
Returns an NSData for sha1 hash.
*/
- (NSData *)sha1Data;
/**
Returns a lowercase NSString for sha224 hash.
*/
- (NSString *)sha224String;
/**
Returns an NSData for sha224 hash.
*/
- (NSData *)sha224Data;
/**
Returns a lowercase NSString for sha256 hash.
*/
- (NSString *)sha256String;
/**
Returns an NSData for sha256 hash.
*/
- (NSData *)sha256Data;
/**
Returns a lowercase NSString for sha384 hash.
*/
- (NSString *)sha384String;
/**
Returns an NSData for sha384 hash.
*/
- (NSData *)sha384Data;
/**
Returns a lowercase NSString for sha512 hash.
*/
- (NSString *)sha512String;
/**
Returns an NSData for sha512 hash.
*/
- (NSData *)sha512Data;
/**
Returns a lowercase NSString for hmac using algorithm md5 with key.
@param key The hmac key.
*/
- (NSString *)hmacMD5StringWithKey:(NSString *)key;
/**
Returns an NSData for hmac using algorithm md5 with key.
@param key The hmac key.
*/
- (NSData *)hmacMD5DataWithKey:(NSData *)key;
/**
Returns a lowercase NSString for hmac using algorithm sha1 with key.
@param key The hmac key.
*/
- (NSString *)hmacSHA1StringWithKey:(NSString *)key;
/**
Returns an NSData for hmac using algorithm sha1 with key.
@param key The hmac key.
*/
- (NSData *)hmacSHA1DataWithKey:(NSData *)key;
/**
Returns a lowercase NSString for hmac using algorithm sha224 with key.
@param key The hmac key.
*/
- (NSString *)hmacSHA224StringWithKey:(NSString *)key;
/**
Returns an NSData for hmac using algorithm sha224 with key.
@param key The hmac key.
*/
- (NSData *)hmacSHA224DataWithKey:(NSData *)key;
/**
Returns a lowercase NSString for hmac using algorithm sha256 with key.
@param key The hmac key.
*/
- (NSString *)hmacSHA256StringWithKey:(NSString *)key;
/**
Returns an NSData for hmac using algorithm sha256 with key.
@param key The hmac key.
*/
- (NSData *)hmacSHA256DataWithKey:(NSData *)key;
/**
Returns a lowercase NSString for hmac using algorithm sha384 with key.
@param key The hmac key.
*/
- (NSString *)hmacSHA384StringWithKey:(NSString *)key;
/**
Returns an NSData for hmac using algorithm sha384 with key.
@param key The hmac key.
*/
- (NSData *)hmacSHA384DataWithKey:(NSData *)key;
/**
Returns a lowercase NSString for hmac using algorithm sha512 with key.
@param key The hmac key.
*/
- (NSString *)hmacSHA512StringWithKey:(NSString *)key;
/**
Returns an NSData for hmac using algorithm sha512 with key.
@param key The hmac key.
*/
- (NSData *)hmacSHA512DataWithKey:(NSData *)key;
/**
Returns a lowercase NSString for crc32 hash.
*/
- (NSString *)crc32String;
/**
Returns crc32 hash.
*/
- (uint32_t)crc32;
#pragma mark - Encrypt and Decrypt
///=============================================================================
/// @name Encrypt and Decrypt
///=============================================================================
/**
Returns an encrypted NSData using AES.
@param key A key length of 16, 24 or 32 (128, 192 or 256bits).
@param iv An initialization vector length of 16(128bits).
Pass nil when you don't want to use iv.
@return An NSData encrypted, or nil if an error occurs.
*/
- (nullable NSData *)aes256EncryptWithKey:(NSData *)key iv:(nullable NSData *)iv;
/**
Returns an decrypted NSData using AES.
@param key A key length of 16, 24 or 32 (128, 192 or 256bits).
@param iv An initialization vector length of 16(128bits).
Pass nil when you don't want to use iv.
@return An NSData decrypted, or nil if an error occurs.
*/
- (nullable NSData *)aes256DecryptWithkey:(NSData *)key iv:(nullable NSData *)iv;
#pragma mark - Encode and decode
///=============================================================================
/// @name Encode and decode
///=============================================================================
/**
Returns string decoded in UTF8.
*/
- (nullable NSString *)utf8String;
/**
Returns a uppercase NSString in HEX.
*/
- (nullable NSString *)hexString;
/**
Returns an NSData from hex string.
@param hexString The hex string which is case insensitive.
@return a new NSData, or nil if an error occurs.
*/
+ (nullable NSData *)dataWithHexString:(NSString *)hexString;
/**
Returns an NSString for base64 encoded.
*/
- (nullable NSString *)base64EncodedString;
/**
Returns an NSData from base64 encoded string.
@warning This method has been implemented in iOS7.
@param base64EncodedString The encoded string.
*/
+ (nullable NSData *)dataWithBase64EncodedString:(NSString *)base64EncodedString;
/**
Returns an NSDictionary or NSArray for decoded self.
Returns nil if an error occurs.
*/
- (nullable id)jsonValueDecoded;
#pragma mark - Inflate and deflate
///=============================================================================
/// @name Inflate and deflate
///=============================================================================
/**
Decompress data from gzip data.
@return Inflated data.
*/
- (nullable NSData *)gzipInflate;
/**
Comperss data to gzip in default compresssion level.
@return Deflated data.
*/
- (nullable NSData *)gzipDeflate;
/**
Decompress data from zlib-compressed data.
@return Inflated data.
*/
- (nullable NSData *)zlibInflate;
/**
Comperss data to zlib-compressed in default compresssion level.
@return Deflated data.
*/
- (nullable NSData *)zlibDeflate;
#pragma mark - Others
///=============================================================================
/// @name Others
///=============================================================================
/**
Create data from the file in main bundle (similar to [UIImage imageNamed:]).
@param name The file name (in main bundle).
@return A new data create from the file.
*/
+ (nullable NSData *)dataNamed:(NSString *)name;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/WeChat/ThirdLib/YYKit/Base/Foundation/NSData+YYAdd.h
|
objective-c
| 2016-06-06T01:53:42
| 2024-08-05T09:45:48
|
WeChat
|
zhengwenming/WeChat
| 1,626
| 1,553
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.