text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```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" #if SD_UIKIT #import "SDWebImageManager.h" /** * Integrates SDWebImage async downloading and caching of remote images with UIButtonView. */ @interface UIButton (WebCache) /** * Get the current image URL. */ - (nullable NSURL *)sd_currentImageURL; #pragma mark - Image /** * 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. */ - (nullable 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:(nullable 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:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable 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:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable 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 retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state completed:(nullable SDExternalCompletionBlock)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 retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)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 retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock; #pragma mark - Background image /** * 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:(nullable 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:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable 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:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable 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 retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state completed:(nullable SDExternalCompletionBlock)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 retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)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 retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url forState:(UIControlState)state placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock; #pragma mark - Cancel /** * Cancel the current image download */ - (void)sd_cancelImageLoadForState:(UIControlState)state; /** * Cancel the current backgroundImage download */ - (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state; @end #endif ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/UIButton+WebCache.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,194
```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 "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) + (nullable UIImage *)sd_imageWithData:(nullable NSData *)data { if (!data) { return nil; } UIImage *image; SDImageFormat imageFormat = [NSData sd_imageFormatForImageData:data]; if (imageFormat == SDImageFormatGIF) { image = [UIImage sd_animatedGIFWithData:data]; } #ifdef SD_WEBP else if (imageFormat == SDImageFormatWebP) { image = [UIImage sd_imageWithWebPData:data]; } #endif else { image = [[UIImage alloc] initWithData:data]; #if SD_UIKIT || SD_WATCH UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data]; if (orientation != UIImageOrientationUp) { image = [UIImage imageWithCGImage:image.CGImage scale:image.scale orientation:orientation]; } #endif } return image; } #if SD_UIKIT || SD_WATCH +(UIImageOrientation)sd_imageOrientationFromImageData:(nonnull 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; } #endif - (nullable NSData *)sd_imageData { return [self sd_imageDataAsFormat:SDImageFormatUndefined]; } - (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat { NSData *imageData = nil; if (self) { #if SD_UIKIT || SD_WATCH int alphaInfo = CGImageGetAlphaInfo(self.CGImage); BOOL hasAlpha = !(alphaInfo == kCGImageAlphaNone || alphaInfo == kCGImageAlphaNoneSkipFirst || alphaInfo == kCGImageAlphaNoneSkipLast); BOOL usePNG = hasAlpha; // the imageFormat param has priority here. But if the format is undefined, we relly on the alpha channel if (imageFormat != SDImageFormatUndefined) { usePNG = (imageFormat == SDImageFormatPNG); } if (usePNG) { imageData = UIImagePNGRepresentation(self); } else { imageData = UIImageJPEGRepresentation(self, (CGFloat)1.0); } #else NSBitmapImageFileType imageFileType = NSJPEGFileType; if (imageFormat == SDImageFormatGIF) { imageFileType = NSGIFFileType; } else if (imageFormat == SDImageFormatPNG) { imageFileType = NSPNGFileType; } imageData = [NSBitmapImageRep representationOfImageRepsInArray:self.representations usingType:imageFileType properties:@{}]; #endif } return imageData; } @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/UIImage+MultiFormat.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,041
```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 "SDWebImageCompat.h" @class SDImageCacheConfig; typedef NS_ENUM(NSInteger, SDImageCacheType) { /** * The image wasn't available the SDWebImage caches, but was downloaded from the web. */ SDImageCacheTypeNone, /** * The image was obtained from the disk cache. */ SDImageCacheTypeDisk, /** * The image was obtained from the memory cache. */ SDImageCacheTypeMemory }; typedef void(^SDCacheQueryCompletedBlock)(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType); typedef void(^SDWebImageCheckCacheCompletionBlock)(BOOL isInCache); typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize); /** * SDImageCache maintains a memory cache and an optional disk cache. Disk cache write operations are performed * asynchronous so it doesnt add unnecessary latency to the UI. */ @interface SDImageCache : NSObject #pragma mark - Properties /** * Cache Config object - storing all kind of settings */ @property (nonatomic, nonnull, readonly) SDImageCacheConfig *config; /** * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory. */ @property (assign, nonatomic) NSUInteger maxMemoryCost; /** * The maximum number of objects the cache should hold. */ @property (assign, nonatomic) NSUInteger maxMemoryCountLimit; #pragma mark - Singleton and initialization /** * Returns global shared cache instance * * @return SDImageCache global instance */ + (nonnull instancetype)sharedImageCache; /** * Init a new cache store with a specific namespace * * @param ns The namespace to use for this cache store */ - (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns; /** * Init a new cache store with a specific namespace and directory * * @param ns The namespace to use for this cache store * @param directory Directory to cache disk images in */ - (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns diskCacheDirectory:(nonnull NSString *)directory NS_DESIGNATED_INITIALIZER; #pragma mark - Cache paths - (nullable NSString *)makeDiskCachePath:(nonnull NSString*)fullNamespace; /** * Add a read-only cache path to search for images pre-cached by SDImageCache * Useful if you want to bundle pre-loaded images with your app * * @param path The path to use for this read-only cache path */ - (void)addReadOnlyCachePath:(nonnull NSString *)path; #pragma mark - Store Ops /** * Asynchronously store an image into memory and disk cache at the given key. * * @param image The image to store * @param key The unique image cache key, usually it's image absolute URL * @param completionBlock A block executed after the operation is finished */ - (void)storeImage:(nullable UIImage *)image forKey:(nullable NSString *)key completion:(nullable SDWebImageNoParamsBlock)completionBlock; /** * Asynchronously store an image into memory and disk cache at the given key. * * @param image The image to store * @param key The unique image cache key, usually it's image absolute URL * @param toDisk Store the image to disk cache if YES * @param completionBlock A block executed after the operation is finished */ - (void)storeImage:(nullable UIImage *)image forKey:(nullable NSString *)key toDisk:(BOOL)toDisk completion:(nullable SDWebImageNoParamsBlock)completionBlock; /** * Asynchronously store an image into memory and disk cache at the given key. * * @param image The image to store * @param imageData The image data as returned by the server, this representation will be used for disk storage * instead of converting the given image object into a storable/compressed image format in order * to save quality and CPU * @param key The unique image cache key, usually it's image absolute URL * @param toDisk Store the image to disk cache if YES * @param completionBlock A block executed after the operation is finished */ - (void)storeImage:(nullable UIImage *)image imageData:(nullable NSData *)imageData forKey:(nullable NSString *)key toDisk:(BOOL)toDisk completion:(nullable SDWebImageNoParamsBlock)completionBlock; /** * Synchronously store image NSData into disk cache at the given key. * * @warning This method is synchronous, make sure to call it from the ioQueue * * @param imageData The image data to store * @param key The unique image cache key, usually it's image absolute URL */ - (void)storeImageDataToDisk:(nullable NSData *)imageData forKey:(nullable NSString *)key; #pragma mark - Query and Retrieve Ops /** * Async check if image exists in disk cache already (does not load the image) * * @param key the key describing the url * @param completionBlock the block to be executed when the check is done. * @note the completion block will be always executed on the main queue */ - (void)diskImageExistsWithKey:(nullable NSString *)key completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock; /** * Operation that queries the cache asynchronously and call the completion when done. * * @param key The unique key used to store the wanted image * @param doneBlock The completion block. Will not get called if the operation is cancelled * * @return a NSOperation instance containing the cache op */ - (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key done:(nullable SDCacheQueryCompletedBlock)doneBlock; /** * Query the memory cache synchronously. * * @param key The unique key used to store the image */ - (nullable UIImage *)imageFromMemoryCacheForKey:(nullable NSString *)key; /** * Query the disk cache synchronously. * * @param key The unique key used to store the image */ - (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key; /** * Query the cache (memory and or disk) synchronously after checking the memory cache. * * @param key The unique key used to store the image */ - (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key; #pragma mark - Remove Ops /** * Remove the image from memory and disk cache asynchronously * * @param key The unique image cache key * @param completion A block that should be executed after the image has been removed (optional) */ - (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion; /** * Remove the image from memory and optionally disk cache asynchronously * * @param key The unique image cache key * @param fromDisk Also remove cache entry from disk if YES * @param completion A block that should be executed after the image has been removed (optional) */ - (void)removeImageForKey:(nullable NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion; #pragma mark - Cache clean Ops /** * Clear all memory cached images */ - (void)clearMemory; /** * Async clear all disk cached images. Non-blocking method - returns immediately. * @param completion A block that should be executed after cache expiration completes (optional) */ - (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion; /** * Async remove all expired cached image from disk. Non-blocking method - returns immediately. * @param completionBlock A block that should be executed after cache expiration completes (optional) */ - (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock; #pragma mark - Cache Info /** * Get the size used by the disk cache */ - (NSUInteger)getSize; /** * Get the number of images in the disk cache */ - (NSUInteger)getDiskCount; /** * Asynchronously calculate the disk cache's size. */ - (void)calculateSizeWithCompletionBlock:(nullable SDWebImageCalculateSizeBlock)completionBlock; #pragma mark - Cache Paths /** * Get the cache path for a certain key (needs the cache path root folder) * * @param key the key (can be obtained from url using cacheKeyForURL) * @param path the cache path root folder * * @return the cache path */ - (nullable NSString *)cachePathForKey:(nullable NSString *)key inPath:(nonnull NSString *)path; /** * Get the default cache path for a certain key * * @param key the key (can be obtained from url using cacheKeyForURL) * * @return the default cache path */ - (nullable NSString *)defaultCachePathForKey:(nullable NSString *)key; @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/SDImageCache.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,940
```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" #if SD_UIKIT #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:(nullable 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:(nullable 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 retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)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 retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)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 * @note the progress block is executed on a background queue * @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 retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock; @end #endif ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
821
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * (c) Jamie Pinkham * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import <TargetConditionals.h> #ifdef __OBJC_GC__ #error SDWebImage does not support Objective-C Garbage Collection #endif // Apple's defines from TargetConditionals.h are a bit weird. // Seems like TARGET_OS_MAC is always defined (on all platforms). // To determine if we are running on OSX, we can only relly on TARGET_OS_IPHONE=0 and all the other platforms #if !TARGET_OS_IPHONE && !TARGET_OS_IOS && !TARGET_OS_TV && !TARGET_OS_WATCH #define SD_MAC 1 #else #define SD_MAC 0 #endif // iOS and tvOS are very similar, UIKit exists on both platforms // Note: watchOS also has UIKit, but it's very limited #if TARGET_OS_IOS || TARGET_OS_TV #define SD_UIKIT 1 #else #define SD_UIKIT 0 #endif #if TARGET_OS_IOS #define SD_IOS 1 #else #define SD_IOS 0 #endif #if TARGET_OS_TV #define SD_TV 1 #else #define SD_TV 0 #endif #if TARGET_OS_WATCH #define SD_WATCH 1 #else #define SD_WATCH 0 #endif #if SD_MAC #import <AppKit/AppKit.h> #ifndef UIImage #define UIImage NSImage #endif #ifndef UIImageView #define UIImageView NSImageView #endif #ifndef UIView #define UIView NSView #endif #else #if __IPHONE_OS_VERSION_MIN_REQUIRED != 20000 && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0 #error SDWebImage doesn't support Deployment Target version < 5.0 #endif #if SD_UIKIT #import <UIKit/UIKit.h> #endif #if SD_WATCH #import <WatchKit/WatchKit.h> #endif #endif #ifndef NS_ENUM #define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type #endif #ifndef NS_OPTIONS #define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type #endif #if OS_OBJECT_USE_OBJC #undef SDDispatchQueueRelease #undef SDDispatchQueueSetterSementics #define SDDispatchQueueRelease(q) #define SDDispatchQueueSetterSementics strong #else #undef SDDispatchQueueRelease #undef SDDispatchQueueSetterSementics #define SDDispatchQueueRelease(q) (dispatch_release(q)) #define SDDispatchQueueSetterSementics assign #endif extern UIImage *SDScaledImageForKey(NSString *key, UIImage *image); typedef void(^SDWebImageNoParamsBlock)(); extern NSString *const SDWebImageErrorDomain; #ifndef dispatch_main_async_safe #define dispatch_main_async_safe(block)\ if (strcmp(dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL), dispatch_queue_get_label(dispatch_get_main_queue())) == 0) {\ block();\ } else {\ dispatch_async(dispatch_get_main_queue(), block);\ } #endif static int64_t kAsyncTestTimeout = 5; ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/SDWebImageCompat.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
772
```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> @protocol SDWebImageOperation <NSObject> - (void)cancel; @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/SDWebImageOperation.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
78
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * (c) james <path_to_url * * 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) + (nullable UIImage *)decodedImageWithImage:(nullable UIImage *)image; + (nullable UIImage *)decodedAndScaledDownImageWithImage:(nullable UIImage *)image; @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/SDWebImageDecoder.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
121
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * (c) Fabrice Aneche * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "NSData+ImageContentType.h" @implementation NSData (ImageContentType) + (SDImageFormat)sd_imageFormatForImageData:(nullable NSData *)data { if (!data) { return SDImageFormatUndefined; } uint8_t c; [data getBytes:&c length:1]; switch (c) { case 0xFF: return SDImageFormatJPEG; case 0x89: return SDImageFormatPNG; case 0x47: return SDImageFormatGIF; case 0x49: case 0x4D: return SDImageFormatTIFF; case 0x52: // R as RIFF for WEBP if (data.length < 12) { return SDImageFormatUndefined; } NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding]; if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) { return SDImageFormatWebP; } } return SDImageFormatUndefined; } @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/NSData+ImageContentType.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
312
```objective-c // // SDImageCacheConfig.h // SDWebImage // // Created by Bogdan on 09/09/16. // #import <Foundation/Foundation.h> #import "SDWebImageCompat.h" @interface SDImageCacheConfig : NSObject /** * Decompressing images that are downloaded and cached can improve performance but can consume lot of memory. * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. */ @property (assign, nonatomic) BOOL shouldDecompressImages; /** * disable iCloud backup [defaults to YES] */ @property (assign, nonatomic) BOOL shouldDisableiCloud; /** * use memory cache [defaults to YES] */ @property (assign, nonatomic) BOOL shouldCacheImagesInMemory; /** * The maximum length of time to keep an image in the cache, in seconds */ @property (assign, nonatomic) NSInteger maxCacheAge; /** * The maximum size of the cache, in bytes. */ @property (assign, nonatomic) NSUInteger maxCacheSize; @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/SDImageCacheConfig.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
214
```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 "NSImage+WebCache.h" #if SD_MAC @implementation NSImage (WebCache) - (CGImageRef)CGImage { NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height); CGImageRef cgImage = [self CGImageForProposedRect:&imageRect context:NULL hints:nil]; return cgImage; } - (NSArray<NSImage *> *)images { return nil; } - (BOOL)isGIF { return NO; } @end #endif ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/NSImage+WebCache.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
170
```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> #import "NSImage+WebCache.h" @interface SDWebImageCombinedOperation : NSObject <SDWebImageOperation> @property (assign, nonatomic, getter = isCancelled) BOOL cancelled; @property (copy, nonatomic, nullable) SDWebImageNoParamsBlock cancelBlock; @property (strong, nonatomic, nullable) NSOperation *cacheOperation; @end @interface SDWebImageManager () @property (strong, nonatomic, readwrite, nonnull) SDImageCache *imageCache; @property (strong, nonatomic, readwrite, nonnull) SDWebImageDownloader *imageDownloader; @property (strong, nonatomic, nonnull) NSMutableSet<NSURL *> *failedURLs; @property (strong, nonatomic, nonnull) NSMutableArray<SDWebImageCombinedOperation *> *runningOperations; @end @implementation SDWebImageManager + (nonnull instancetype)sharedManager { static dispatch_once_t once; static id instance; dispatch_once(&once, ^{ instance = [self new]; }); return instance; } - (nonnull instancetype)init { SDImageCache *cache = [SDImageCache sharedImageCache]; SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader]; return [self initWithCache:cache downloader:downloader]; } - (nonnull instancetype)initWithCache:(nonnull SDImageCache *)cache downloader:(nonnull SDWebImageDownloader *)downloader { if ((self = [super init])) { _imageCache = cache; _imageDownloader = downloader; _failedURLs = [NSMutableSet new]; _runningOperations = [NSMutableArray new]; } return self; } - (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url { if (!url) { return @""; } if (self.cacheKeyFilter) { return self.cacheKeyFilter(url); } else { return url.absoluteString; } } - (void)cachedImageExistsForURL:(nullable NSURL *)url completion:(nullable 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:(nullable NSURL *)url completion:(nullable 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>)loadImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDInternalCompletionBlock)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; if (url) { @synchronized (self.failedURLs) { isFailedUrl = [self.failedURLs containsObject:url]; } } if (url.absoluteString.length == 0 || (!(options & SDWebImageRetryFailed) && isFailedUrl)) { [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil] url:url]; return operation; } @synchronized (self.runningOperations) { [self.runningOperations addObject:operation]; } NSString *key = [self cacheKeyForURL:url]; operation.cacheOperation = [self.imageCache queryCacheOperationForKey:key done:^(UIImage *cachedImage, NSData *cachedData, SDImageCacheType cacheType) { if (operation.isCancelled) { [self safelyRemoveOperationFromRunning:operation]; return; } if ((!cachedImage || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) { if (cachedImage && options & SDWebImageRefreshCached) { // If image was found in the cache but 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. [self callCompletionBlockForOperation:weakOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url: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 (options & SDWebImageScaleDownLargeImages) downloaderOptions |= SDWebImageDownloaderScaleDownLargeImages; if (cachedImage && 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; } SDWebImageDownloadToken *subOperationToken = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *downloadedData, NSError *error, BOOL finished) { __strong __typeof(weakOperation) strongOperation = weakOperation; if (!strongOperation || strongOperation.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) { [self callCompletionBlockForOperation:strongOperation completion:completedBlock error:error url:url]; if ( error.code != NSURLErrorNotConnectedToInternet && error.code != NSURLErrorCancelled && error.code != NSURLErrorTimedOut && error.code != NSURLErrorInternationalRoamingOff && error.code != NSURLErrorDataNotAllowed && error.code != NSURLErrorCannotFindHost && error.code != NSURLErrorCannotConnectToHost) { @synchronized (self.failedURLs) { [self.failedURLs addObject:url]; } } } else { if ((options & SDWebImageRetryFailed)) { @synchronized (self.failedURLs) { [self.failedURLs removeObject:url]; } } BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly); if (options & SDWebImageRefreshCached && cachedImage && !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]; // pass nil if the image was transformed, so we can recalculate the data from the image [self.imageCache storeImage:transformedImage imageData:(imageWasTransformed ? nil : downloadedData) forKey:key toDisk:cacheOnDisk completion:nil]; } [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:transformedImage data:downloadedData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url]; }); } else { if (downloadedImage && finished) { [self.imageCache storeImage:downloadedImage imageData:downloadedData forKey:key toDisk:cacheOnDisk completion:nil]; } [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:downloadedImage data:downloadedData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url]; } } if (finished) { [self safelyRemoveOperationFromRunning:strongOperation]; } }]; operation.cancelBlock = ^{ [self.imageDownloader cancel:subOperationToken]; __strong __typeof(weakOperation) strongOperation = weakOperation; [self safelyRemoveOperationFromRunning:strongOperation]; }; } else if (cachedImage) { __strong __typeof(weakOperation) strongOperation = weakOperation; [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url]; [self safelyRemoveOperationFromRunning:operation]; } else { // Image not in cache and download disallowed by delegate __strong __typeof(weakOperation) strongOperation = weakOperation; [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:nil data:nil error:nil cacheType:SDImageCacheTypeNone finished:YES url:url]; [self safelyRemoveOperationFromRunning:operation]; } }]; return operation; } - (void)saveImageToCache:(nullable UIImage *)image forURL:(nullable NSURL *)url { if (image && url) { NSString *key = [self cacheKeyForURL:url]; [self.imageCache storeImage:image forKey:key toDisk:YES completion:nil]; } } - (void)cancelAll { @synchronized (self.runningOperations) { NSArray<SDWebImageCombinedOperation *> *copiedOperations = [self.runningOperations copy]; [copiedOperations makeObjectsPerformSelector:@selector(cancel)]; [self.runningOperations removeObjectsInArray:copiedOperations]; } } - (BOOL)isRunning { BOOL isRunning = NO; @synchronized (self.runningOperations) { isRunning = (self.runningOperations.count > 0); } return isRunning; } - (void)safelyRemoveOperationFromRunning:(nullable SDWebImageCombinedOperation*)operation { @synchronized (self.runningOperations) { if (operation) { [self.runningOperations removeObject:operation]; } } } - (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation completion:(nullable SDInternalCompletionBlock)completionBlock error:(nullable NSError *)error url:(nullable NSURL *)url { [self callCompletionBlockForOperation:operation completion:completionBlock image:nil data:nil error:error cacheType:SDImageCacheTypeNone finished:YES url:url]; } - (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation completion:(nullable SDInternalCompletionBlock)completionBlock image:(nullable UIImage *)image data:(nullable NSData *)data error:(nullable NSError *)error cacheType:(SDImageCacheType)cacheType finished:(BOOL)finished url:(nullable NSURL *)url { dispatch_main_async_safe(^{ if (operation && !operation.isCancelled && completionBlock) { completionBlock(image, data, error, cacheType, finished, url); } }); } @end @implementation SDWebImageCombinedOperation - (void)setCancelBlock:(nullable 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 ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/SDWebImageManager.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
3,167
```objective-c // // SDImageCacheConfig.m // SDWebImage // // Created by Bogdan on 09/09/16. // #import "SDImageCacheConfig.h" static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week @implementation SDImageCacheConfig - (instancetype)init { if (self = [super init]) { _shouldDecompressImages = YES; _shouldDisableiCloud = YES; _shouldCacheImagesInMemory = YES; _maxCacheAge = kDefaultCacheMaxCacheAge; _maxCacheSize = 0; } return self; } @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/SDImageCacheConfig.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
148
```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" #if SD_UIKIT || SD_MAC #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) /** * Set the imageView `image` with an `url`. * * The download is asynchronous and cached. * * @param url The url for the image. */ - (void)sd_setImageWithURL:(nullable 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:(nullable NSURL *)url placeholderImage:(nullable 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:(nullable NSURL *)url placeholderImage:(nullable 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 retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)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 retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder completed:(nullable SDExternalCompletionBlock)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 retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)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 * @note the progress block is executed on a background queue * @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 retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock; /** * Set the imageView `image` with an `url` and optionally a 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 * @note the progress block is executed on a background queue * @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 retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_setImageWithPreviousCachedImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock; #if SD_UIKIT #pragma mark - Animation of multiple images /** * Download an array of images and starts them in an animation loop * * @param arrayOfURLs An array of NSURL */ - (void)sd_setAnimationImagesWithURLs:(nonnull NSArray<NSURL *> *)arrayOfURLs; - (void)sd_cancelCurrentAnimationImagesLoad; #endif @end #endif ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/UIImageView+WebCache.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,681
```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" extern NSString * _Nonnull const SDWebImageDownloadStartNotification; extern NSString * _Nonnull const SDWebImageDownloadReceiveResponseNotification; extern NSString * _Nonnull const SDWebImageDownloadStopNotification; extern NSString * _Nonnull const SDWebImageDownloadFinishNotification; /** Describes a downloader operation. If one wants to use a custom downloader op, it needs to inherit from `NSOperation` and conform to this protocol */ @protocol SDWebImageDownloaderOperationInterface<NSObject> - (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request inSession:(nullable NSURLSession *)session options:(SDWebImageDownloaderOptions)options; - (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; - (BOOL)shouldDecompressImages; - (void)setShouldDecompressImages:(BOOL)value; - (nullable NSURLCredential *)credential; - (void)setCredential:(nullable NSURLCredential *)value; @end @interface SDWebImageDownloaderOperation : NSOperation <SDWebImageDownloaderOperationInterface, SDWebImageOperation, NSURLSessionTaskDelegate, NSURLSessionDataDelegate> /** * The request used by the operation's task. */ @property (strong, nonatomic, readonly, nullable) NSURLRequest *request; /** * The operation's task */ @property (strong, nonatomic, readonly, nullable) NSURLSessionTask *dataTask; @property (assign, nonatomic) BOOL shouldDecompressImages; /** * Was used to determine whether the URL connection should consult the credential storage for authenticating the connection. * @deprecated Not used for a couple of versions */ @property (nonatomic, assign) BOOL shouldUseCredentialStorage __deprecated_msg("Property deprecated. Does nothing. Kept only for backwards compatibility"); /** * 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, nullable) NSURLCredential *credential; /** * The SDWebImageDownloaderOptions for the receiver. */ @property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; /** * The expected size of data. */ @property (assign, nonatomic) NSInteger expectedSize; /** * The response returned by the operation's connection. */ @property (strong, nonatomic, nullable) NSURLResponse *response; /** * Initializes a `SDWebImageDownloaderOperation` object * * @see SDWebImageDownloaderOperation * * @param request the URL request * @param session the URL session in which this operation will run * @param options downloader options * * @return the initialized instance */ - (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request inSession:(nullable NSURLSession *)session options:(SDWebImageDownloaderOptions)options NS_DESIGNATED_INITIALIZER; /** * Adds handlers for progress and completion. Returns a tokent that can be passed to -cancel: to cancel this set of * callbacks. * * @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 * * @return the token to use to cancel this set of handlers */ - (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; /** * Cancels a set of callbacks. Once all callbacks are canceled, the operation is cancelled. * * @param token the token representing a set of callbacks to cancel * * @return YES if the operation was stopped because this was the last token to be canceled. NO otherwise. */ - (BOOL)cancel:(nullable id)token; @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
933
```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> @implementation SDWebImageDownloadToken @end @interface SDWebImageDownloader () <NSURLSessionTaskDelegate, NSURLSessionDataDelegate> @property (strong, nonatomic, nonnull) NSOperationQueue *downloadQueue; @property (weak, nonatomic, nullable) NSOperation *lastAddedOperation; @property (assign, nonatomic, nullable) Class operationClass; @property (strong, nonatomic, nonnull) NSMutableDictionary<NSURL *, SDWebImageDownloaderOperation *> *URLOperations; @property (strong, nonatomic, nullable) SDHTTPHeadersMutableDictionary *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, nullable) dispatch_queue_t barrierQueue; // The session in which data tasks will run @property (strong, nonatomic) NSURLSession *session; @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]; } } + (nonnull instancetype)sharedDownloader { static dispatch_once_t once; static id instance; dispatch_once(&once, ^{ instance = [self new]; }); return instance; } - (nonnull instancetype)init { return [self initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; } - (nonnull instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)sessionConfiguration { if ((self = [super init])) { _operationClass = [SDWebImageDownloaderOperation class]; _shouldDecompressImages = YES; _executionOrder = SDWebImageDownloaderFIFOExecutionOrder; _downloadQueue = [NSOperationQueue new]; _downloadQueue.maxConcurrentOperationCount = 6; _downloadQueue.name = @"com.hackemist.SDWebImageDownloader"; _URLOperations = [NSMutableDictionary new]; #ifdef SD_WEBP _HTTPHeaders = [@{@"Accept": @"image/webp,image/*;q=0.8"} mutableCopy]; #else _HTTPHeaders = [@{@"Accept": @"image/*;q=0.8"} mutableCopy]; #endif _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT); _downloadTimeout = 15.0; sessionConfiguration.timeoutIntervalForRequest = _downloadTimeout; /** * Create the session for this task * We send nil as delegate queue so that the session creates a serial operation queue for performing all delegate * method calls and completion handler calls. */ self.session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil]; } return self; } - (void)dealloc { [self.session invalidateAndCancel]; self.session = nil; [self.downloadQueue cancelAllOperations]; SDDispatchQueueRelease(_barrierQueue); } - (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)field { if (value) { self.HTTPHeaders[field] = value; } else { [self.HTTPHeaders removeObjectForKey:field]; } } - (nullable NSString *)valueForHTTPHeaderField:(nullable 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:(nullable Class)operationClass { if (operationClass && [operationClass isSubclassOfClass:[NSOperation class]] && [operationClass conformsToProtocol:@protocol(SDWebImageDownloaderOperationInterface)]) { _operationClass = operationClass; } else { _operationClass = [SDWebImageDownloaderOperation class]; } } - (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock { __weak SDWebImageDownloader *wself = self; return [self addProgressCallback:progressBlock completedBlock:completedBlock forURL:url createCallback:^SDWebImageDownloaderOperation *{ __strong __typeof (wself) sself = wself; NSTimeInterval timeoutInterval = sself.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 (sself.headersFilter) { request.allHTTPHeaderFields = sself.headersFilter(url, [sself.HTTPHeaders copy]); } else { request.allHTTPHeaderFields = sself.HTTPHeaders; } SDWebImageDownloaderOperation *operation = [[sself.operationClass alloc] initWithRequest:request inSession:sself.session options:options]; operation.shouldDecompressImages = sself.shouldDecompressImages; if (sself.urlCredential) { operation.credential = sself.urlCredential; } else if (sself.username && sself.password) { operation.credential = [NSURLCredential credentialWithUser:sself.username password:sself.password persistence:NSURLCredentialPersistenceForSession]; } if (options & SDWebImageDownloaderHighPriority) { operation.queuePriority = NSOperationQueuePriorityHigh; } else if (options & SDWebImageDownloaderLowPriority) { operation.queuePriority = NSOperationQueuePriorityLow; } [sself.downloadQueue addOperation:operation]; if (sself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) { // Emulate LIFO execution order by systematically adding new operations as last operation's dependency [sself.lastAddedOperation addDependency:operation]; sself.lastAddedOperation = operation; } return operation; }]; } - (void)cancel:(nullable SDWebImageDownloadToken *)token { dispatch_barrier_async(self.barrierQueue, ^{ SDWebImageDownloaderOperation *operation = self.URLOperations[token.url]; BOOL canceled = [operation cancel:token.downloadOperationCancelToken]; if (canceled) { [self.URLOperations removeObjectForKey:token.url]; } }); } - (nullable SDWebImageDownloadToken *)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock completedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock forURL:(nullable NSURL *)url createCallback:(SDWebImageDownloaderOperation *(^)())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 nil; } __block SDWebImageDownloadToken *token = nil; dispatch_barrier_sync(self.barrierQueue, ^{ SDWebImageDownloaderOperation *operation = self.URLOperations[url]; if (!operation) { operation = createCallback(); self.URLOperations[url] = operation; __weak SDWebImageDownloaderOperation *woperation = operation; operation.completionBlock = ^{ SDWebImageDownloaderOperation *soperation = woperation; if (!soperation) return; if (self.URLOperations[url] == soperation) { [self.URLOperations removeObjectForKey:url]; }; }; } id downloadOperationCancelToken = [operation addHandlersForProgress:progressBlock completed:completedBlock]; token = [SDWebImageDownloadToken new]; token.url = url; token.downloadOperationCancelToken = downloadOperationCancelToken; }); return token; } - (void)setSuspended:(BOOL)suspended { (self.downloadQueue).suspended = suspended; } - (void)cancelAllDownloads { [self.downloadQueue cancelAllOperations]; } #pragma mark Helper methods - (SDWebImageDownloaderOperation *)operationWithTask:(NSURLSessionTask *)task { SDWebImageDownloaderOperation *returnOperation = nil; for (SDWebImageDownloaderOperation *operation in self.downloadQueue.operations) { if (operation.dataTask.taskIdentifier == task.taskIdentifier) { returnOperation = operation; break; } } return returnOperation; } #pragma mark NSURLSessionDataDelegate - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler { // Identify the operation that runs this task and pass it the delegate method SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:dataTask]; [dataOperation URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler]; } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { // Identify the operation that runs this task and pass it the delegate method SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:dataTask]; [dataOperation URLSession:session dataTask:dataTask didReceiveData:data]; } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask willCacheResponse:(NSCachedURLResponse *)proposedResponse completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler { // Identify the operation that runs this task and pass it the delegate method SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:dataTask]; [dataOperation URLSession:session dataTask:dataTask willCacheResponse:proposedResponse completionHandler:completionHandler]; } #pragma mark NSURLSessionTaskDelegate - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { // Identify the operation that runs this task and pass it the delegate method SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:task]; [dataOperation URLSession:session task:task didCompleteWithError:error]; } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler { completionHandler(request); } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { // Identify the operation that runs this task and pass it the delegate method SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:task]; [dataOperation URLSession:session task:task didReceiveChallenge:challenge completionHandler:completionHandler]; } @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/SDWebImageDownloader.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,718
```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 embedded 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 certificates. * Useful for testing purposes. Use with caution in production. */ SDWebImageAllowInvalidSSLCertificates = 1 << 7, /** * By default, images are loaded in the order in which they were queued. This flag moves them to * the front of the queue. */ 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, /** * By default, image is added to the imageView after download. But in some cases, we want to * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance) * Use this flag if you want to manually set the image in the completion when success */ SDWebImageAvoidAutoSetImage = 1 << 11, /** * By default, images are decoded respecting their original size. On iOS, this flag will scale down the * images to a size compatible with the constrained memory of devices. * If `SDWebImageProgressiveDownload` flag is set the scale down is deactivated. */ SDWebImageScaleDownLargeImages = 1 << 12 }; typedef void(^SDExternalCompletionBlock)(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL); typedef void(^SDInternalCompletionBlock)(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL); typedef NSString * _Nullable (^SDWebImageCacheKeyFilterBlock)(NSURL * _Nullable 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:(nonnull SDWebImageManager *)imageManager shouldDownloadImageForURL:(nullable 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. */ - (nullable UIImage *)imageManager:(nonnull SDWebImageManager *)imageManager transformDownloadedImage:(nullable UIImage *)image withURL:(nullable 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 loadImageWithURL: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, nullable) id <SDWebImageManagerDelegate> delegate; @property (strong, nonatomic, readonly, nullable) SDImageCache *imageCache; @property (strong, nonatomic, readonly, nullable) 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, nullable) SDWebImageCacheKeyFilterBlock cacheKeyFilter; /** * Returns global SDWebImageManager instance. * * @return SDWebImageManager shared instance */ + (nonnull instancetype)sharedManager; /** * Allows to specify instance of cache and image downloader used with image manager. * @return new instance of `SDWebImageManager` with specified cache and downloader. */ - (nonnull instancetype)initWithCache:(nonnull SDImageCache *)cache downloader:(nonnull SDWebImageDownloader *)downloader NS_DESIGNATED_INITIALIZER; /** * 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 * @note the progress block is executed on a background queue * @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 and the NSData representation as second parameter. * In case of error the image parameter is nil and the third parameter may contain an NSError. * * The forth parameter is an `SDImageCacheType` enum indicating if the image was retrieved from the local cache * or from the memory cache or from the network. * * The fith parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is * downloading. This block is thus called repeatedly 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. * * The last parameter is the original image URL * * @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation */ - (nullable id <SDWebImageOperation>)loadImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDInternalCompletionBlock)completedBlock; /** * Saves image to cache for given URL * * @param image The image to cache * @param url The URL to the image * */ - (void)saveImageToCache:(nullable UIImage *)image forURL:(nullable NSURL *)url; /** * Cancel all current operations */ - (void)cancelAll; /** * Check one or more operations running */ - (BOOL)isRunning; /** * 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:(nullable NSURL *)url completion:(nullable 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:(nullable NSURL *)url completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock; /** *Return the cache key for a given URL */ - (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url; @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/SDWebImageManager.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,346
```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" #if SD_UIKIT || SD_MAC #import "SDWebImageManager.h" @interface UIView (WebCacheOperation) /** * Set the image load operation (storage in a UIView based dictionary) * * @param operation the operation * @param key key for storing the operation */ - (void)sd_setImageLoadOperation:(nullable id)operation forKey:(nullable NSString *)key; /** * Cancel all operations for the current UIView and key * * @param key key for identifying the operations */ - (void)sd_cancelImageLoadOperationWithKey:(nullable NSString *)key; /** * Just remove the operations corresponding to the current UIView and key without cancelling them * * @param key key for identifying the operations */ - (void)sd_removeImageLoadOperationWithKey:(nullable NSString *)key; @end #endif ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/UIView+WebCacheOperation.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
241
```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" #if SD_MAC #import <Cocoa/Cocoa.h> @interface NSImage (WebCache) - (CGImageRef)CGImage; - (NSArray<NSImage *> *)images; - (BOOL)isGIF; @end #endif ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/NSImage+WebCache.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
114
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * (c) Laurin Brandner * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageCompat.h" @interface UIImage (GIF) /** * Compatibility method - creates an animated UIImage from an NSData, it will only contain the 1st frame image */ + (UIImage *)sd_animatedGIFWithData:(NSData *)data; /** * Checks if an UIImage instance is a GIF. Will use the `images` array */ - (BOOL)isGIF; @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/UIImage+GIF.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
151
```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> #import "UIImage+GIF.h" #import "NSData+ImageContentType.h" #import "NSImage+WebCache.h" #import "SDImageCacheConfig.h" // See path_to_url for discussion @interface AutoPurgeCache : NSCache @end @implementation AutoPurgeCache - (nonnull instancetype)init { self = [super init]; if (self) { #if SD_UIKIT [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeAllObjects) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; #endif } return self; } - (void)dealloc { #if SD_UIKIT [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; #endif } @end FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) { #if SD_MAC return image.size.height * image.size.width; #elif SD_UIKIT || SD_WATCH return image.size.height * image.size.width * image.scale * image.scale; #endif } @interface SDImageCache () #pragma mark - Properties @property (strong, nonatomic, nonnull) NSCache *memCache; @property (strong, nonatomic, nonnull) NSString *diskCachePath; @property (strong, nonatomic, nullable) NSMutableArray<NSString *> *customPaths; @property (SDDispatchQueueSetterSementics, nonatomic, nullable) dispatch_queue_t ioQueue; @end @implementation SDImageCache { NSFileManager *_fileManager; } #pragma mark - Singleton, init, dealloc + (nonnull instancetype)sharedImageCache { static dispatch_once_t once; static id instance; dispatch_once(&once, ^{ instance = [self new]; }); return instance; } - (instancetype)init { return [self initWithNamespace:@"default"]; } - (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns { NSString *path = [self makeDiskCachePath:ns]; return [self initWithNamespace:ns diskCacheDirectory:path]; } - (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns diskCacheDirectory:(nonnull NSString *)directory { if ((self = [super init])) { NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns]; // Create IO serial queue _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL); _config = [[SDImageCacheConfig alloc] init]; // Init the memory cache _memCache = [[AutoPurgeCache alloc] init]; _memCache.name = fullNamespace; // Init the disk cache if (directory != nil) { _diskCachePath = [directory stringByAppendingPathComponent:fullNamespace]; } else { NSString *path = [self makeDiskCachePath:ns]; _diskCachePath = path; } dispatch_sync(_ioQueue, ^{ _fileManager = [NSFileManager new]; }); #if SD_UIKIT // Subscribe to app events [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearMemory) name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteOldFiles) name:UIApplicationWillTerminateNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backgroundDeleteOldFiles) name:UIApplicationDidEnterBackgroundNotification object:nil]; #endif } return self; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; SDDispatchQueueRelease(_ioQueue); } - (void)checkIfQueueIsIOQueue { const char *currentQueueLabel = dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL); const char *ioQueueLabel = dispatch_queue_get_label(self.ioQueue); if (strcmp(currentQueueLabel, ioQueueLabel) != 0) { NSLog(@"This method should be called from the ioQueue"); } } #pragma mark - Cache paths - (void)addReadOnlyCachePath:(nonnull NSString *)path { if (!self.customPaths) { self.customPaths = [NSMutableArray new]; } if (![self.customPaths containsObject:path]) { [self.customPaths addObject:path]; } } - (nullable NSString *)cachePathForKey:(nullable NSString *)key inPath:(nonnull NSString *)path { NSString *filename = [self cachedFileNameForKey:key]; return [path stringByAppendingPathComponent:filename]; } - (nullable NSString *)defaultCachePathForKey:(nullable NSString *)key { return [self cachePathForKey:key inPath:self.diskCachePath]; } - (nullable NSString *)cachedFileNameForKey:(nullable 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], [key.pathExtension isEqualToString:@""] ? @"" : [NSString stringWithFormat:@".%@", key.pathExtension]]; return filename; } - (nullable NSString *)makeDiskCachePath:(nonnull NSString*)fullNamespace { NSArray<NSString *> *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); return [paths[0] stringByAppendingPathComponent:fullNamespace]; } #pragma mark - Store Ops - (void)storeImage:(nullable UIImage *)image forKey:(nullable NSString *)key completion:(nullable SDWebImageNoParamsBlock)completionBlock { [self storeImage:image imageData:nil forKey:key toDisk:YES completion:completionBlock]; } - (void)storeImage:(nullable UIImage *)image forKey:(nullable NSString *)key toDisk:(BOOL)toDisk completion:(nullable SDWebImageNoParamsBlock)completionBlock { [self storeImage:image imageData:nil forKey:key toDisk:toDisk completion:completionBlock]; } - (void)storeImage:(nullable UIImage *)image imageData:(nullable NSData *)imageData forKey:(nullable NSString *)key toDisk:(BOOL)toDisk completion:(nullable SDWebImageNoParamsBlock)completionBlock { if (!image || !key) { if (completionBlock) { completionBlock(); } return; } // if memory cache is enabled if (self.config.shouldCacheImagesInMemory) { NSUInteger cost = SDCacheCostForImage(image); [self.memCache setObject:image forKey:key cost:cost]; } if (toDisk) { dispatch_async(self.ioQueue, ^{ NSData *data = imageData; if (!data && image) { SDImageFormat imageFormatFromData = [NSData sd_imageFormatForImageData:data]; data = [image sd_imageDataAsFormat:imageFormatFromData]; } [self storeImageDataToDisk:data forKey:key]; if (completionBlock) { dispatch_async(dispatch_get_main_queue(), ^{ completionBlock(); }); } }); } else { if (completionBlock) { completionBlock(); } } } - (void)storeImageDataToDisk:(nullable NSData *)imageData forKey:(nullable NSString *)key { if (!imageData || !key) { return; } [self checkIfQueueIsIOQueue]; if (![_fileManager fileExistsAtPath:_diskCachePath]) { [_fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL]; } // get cache Path for image key NSString *cachePathForKey = [self defaultCachePathForKey:key]; // transform to NSUrl NSURL *fileURL = [NSURL fileURLWithPath:cachePathForKey]; [_fileManager createFileAtPath:cachePathForKey contents:imageData attributes:nil]; // disable iCloud backup if (self.config.shouldDisableiCloud) { [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil]; } } #pragma mark - Query and Retrieve Ops - (void)diskImageExistsWithKey:(nullable NSString *)key completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock { dispatch_async(_ioQueue, ^{ BOOL exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key]]; // fallback because of path_to_url that added the extension to the disk file name // checking the key with and without the extension if (!exists) { exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key].stringByDeletingPathExtension]; } if (completionBlock) { dispatch_async(dispatch_get_main_queue(), ^{ completionBlock(exists); }); } }); } - (nullable UIImage *)imageFromMemoryCacheForKey:(nullable NSString *)key { return [self.memCache objectForKey:key]; } - (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key { UIImage *diskImage = [self diskImageForKey:key]; if (diskImage && self.config.shouldCacheImagesInMemory) { NSUInteger cost = SDCacheCostForImage(diskImage); [self.memCache setObject:diskImage forKey:key cost:cost]; } return diskImage; } - (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key { // First check the in-memory cache... UIImage *image = [self imageFromMemoryCacheForKey:key]; if (image) { return image; } // Second check the disk cache... image = [self imageFromDiskCacheForKey:key]; return image; } - (nullable NSData *)diskImageDataBySearchingAllPathsForKey:(nullable NSString *)key { NSString *defaultPath = [self defaultCachePathForKey:key]; NSData *data = [NSData dataWithContentsOfFile:defaultPath]; if (data) { return data; } // fallback because of path_to_url that added the extension to the disk file name // checking the key with and without the extension data = [NSData dataWithContentsOfFile:defaultPath.stringByDeletingPathExtension]; if (data) { return data; } NSArray<NSString *> *customPaths = [self.customPaths copy]; for (NSString *path in customPaths) { NSString *filePath = [self cachePathForKey:key inPath:path]; NSData *imageData = [NSData dataWithContentsOfFile:filePath]; if (imageData) { return imageData; } // fallback because of path_to_url that added the extension to the disk file name // checking the key with and without the extension imageData = [NSData dataWithContentsOfFile:filePath.stringByDeletingPathExtension]; if (imageData) { return imageData; } } return nil; } - (nullable UIImage *)diskImageForKey:(nullable NSString *)key { NSData *data = [self diskImageDataBySearchingAllPathsForKey:key]; if (data) { UIImage *image = [UIImage sd_imageWithData:data]; image = [self scaledImageForKey:key image:image]; if (self.config.shouldDecompressImages) { image = [UIImage decodedImageWithImage:image]; } return image; } else { return nil; } } - (nullable UIImage *)scaledImageForKey:(nullable NSString *)key image:(nullable UIImage *)image { return SDScaledImageForKey(key, image); } - (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key done:(nullable SDCacheQueryCompletedBlock)doneBlock { if (!key) { if (doneBlock) { doneBlock(nil, nil, SDImageCacheTypeNone); } return nil; } // First check the in-memory cache... UIImage *image = [self imageFromMemoryCacheForKey:key]; if (image) { NSData *diskData = nil; if ([image isGIF]) { diskData = [self diskImageDataBySearchingAllPathsForKey:key]; } if (doneBlock) { doneBlock(image, diskData, SDImageCacheTypeMemory); } return nil; } NSOperation *operation = [NSOperation new]; dispatch_async(self.ioQueue, ^{ if (operation.isCancelled) { // do not call the completion if cancelled return; } @autoreleasepool { NSData *diskData = [self diskImageDataBySearchingAllPathsForKey:key]; UIImage *diskImage = [self diskImageForKey:key]; if (diskImage && self.config.shouldCacheImagesInMemory) { NSUInteger cost = SDCacheCostForImage(diskImage); [self.memCache setObject:diskImage forKey:key cost:cost]; } if (doneBlock) { dispatch_async(dispatch_get_main_queue(), ^{ doneBlock(diskImage, diskData, SDImageCacheTypeDisk); }); } } }); return operation; } #pragma mark - Remove Ops - (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion { [self removeImageForKey:key fromDisk:YES withCompletion:completion]; } - (void)removeImageForKey:(nullable NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion { if (key == nil) { return; } if (self.config.shouldCacheImagesInMemory) { [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(); } } # pragma mark - Mem Cache settings - (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost { self.memCache.totalCostLimit = maxMemoryCost; } - (NSUInteger)maxMemoryCost { return self.memCache.totalCostLimit; } - (NSUInteger)maxMemoryCountLimit { return self.memCache.countLimit; } - (void)setMaxMemoryCountLimit:(NSUInteger)maxCountLimit { self.memCache.countLimit = maxCountLimit; } #pragma mark - Cache clean Ops - (void)clearMemory { [self.memCache removeAllObjects]; } - (void)clearDiskOnCompletion:(nullable 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)deleteOldFiles { [self deleteOldFilesWithCompletionBlock:nil]; } - (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock { dispatch_async(self.ioQueue, ^{ NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; NSArray<NSString *> *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.config.maxCacheAge]; NSMutableDictionary<NSURL *, NSDictionary<NSString *, id> *> *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<NSURL *> *urlsToDelete = [[NSMutableArray alloc] init]; for (NSURL *fileURL in fileEnumerator) { NSError *error; NSDictionary<NSString *, id> *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:&error]; // Skip directories and errors. if (error || !resourceValues || [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[fileURL] = resourceValues; } 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.config.maxCacheSize > 0 && currentCacheSize > self.config.maxCacheSize) { // Target half of our maximum cache size for this cleanup pass. const NSUInteger desiredCacheSize = self.config.maxCacheSize / 2; // Sort the remaining cache files by their last modification time (oldest first). NSArray<NSURL *> *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<NSString *, id> *resourceValues = cacheFiles[fileURL]; NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; currentCacheSize -= totalAllocatedSize.unsignedIntegerValue; if (currentCacheSize < desiredCacheSize) { break; } } } } if (completionBlock) { dispatch_async(dispatch_get_main_queue(), ^{ completionBlock(); }); } }); } #if SD_UIKIT - (void)backgroundDeleteOldFiles { Class UIApplicationClass = NSClassFromString(@"UIApplication"); if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) { return; } UIApplication *application = [UIApplication performSelector:@selector(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 deleteOldFilesWithCompletionBlock:^{ [application endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }]; } #endif #pragma mark - Cache Info - (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<NSString *, id> *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:(nullable 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); }); } }); } @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/SDImageCache.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
4,672
```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 "SDWebImageCompat.h" #import "SDWebImageOperation.h" typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) { SDWebImageDownloaderLowPriority = 1 << 0, SDWebImageDownloaderProgressiveDownload = 1 << 1, /** * By default, request prevent the use of NSURLCache. With this flag, NSURLCache * is used with default policies. */ SDWebImageDownloaderUseNSURLCache = 1 << 2, /** * Call completion block with nil image/imageData if the image was read from NSURLCache * (to be combined with `SDWebImageDownloaderUseNSURLCache`). */ SDWebImageDownloaderIgnoreCachedResponse = 1 << 3, /** * 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. */ SDWebImageDownloaderContinueInBackground = 1 << 4, /** * Handles cookies stored in NSHTTPCookieStore by setting * NSMutableURLRequest.HTTPShouldHandleCookies = YES; */ SDWebImageDownloaderHandleCookies = 1 << 5, /** * Enable to allow untrusted SSL certificates. * Useful for testing purposes. Use with caution in production. */ SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6, /** * Put the image in the high priority queue. */ SDWebImageDownloaderHighPriority = 1 << 7, /** * Scale down the image */ SDWebImageDownloaderScaleDownLargeImages = 1 << 8, }; typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) { /** * Default value. All download operations will execute in queue style (first-in-first-out). */ SDWebImageDownloaderFIFOExecutionOrder, /** * All download operations will execute in stack style (last-in-first-out). */ SDWebImageDownloaderLIFOExecutionOrder }; extern NSString * _Nonnull const SDWebImageDownloadStartNotification; extern NSString * _Nonnull const SDWebImageDownloadStopNotification; typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL); typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished); typedef NSDictionary<NSString *, NSString *> SDHTTPHeadersDictionary; typedef NSMutableDictionary<NSString *, NSString *> SDHTTPHeadersMutableDictionary; typedef SDHTTPHeadersDictionary * _Nullable (^SDWebImageDownloaderHeadersFilterBlock)(NSURL * _Nullable url, SDHTTPHeadersDictionary * _Nullable headers); /** * A token associated with each download. Can be used to cancel a download */ @interface SDWebImageDownloadToken : NSObject @property (nonatomic, strong, nullable) NSURL *url; @property (nonatomic, strong, nullable) id downloadOperationCancelToken; @end /** * Asynchronous downloader dedicated and optimized for image loading. */ @interface SDWebImageDownloader : NSObject /** * Decompressing images that are downloaded and cached can improve performance but can consume lot of memory. * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. */ @property (assign, nonatomic) BOOL shouldDecompressImages; /** * The maximum number of concurrent downloads */ @property (assign, nonatomic) NSInteger maxConcurrentDownloads; /** * Shows the current amount of downloads that still need to be downloaded */ @property (readonly, nonatomic) NSUInteger currentDownloadCount; /** * The timeout value (in seconds) for the download operation. Default: 15.0. */ @property (assign, nonatomic) NSTimeInterval downloadTimeout; /** * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`. */ @property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; /** * Singleton method, returns the shared instance * * @return global shared instance of downloader class */ + (nonnull instancetype)sharedDownloader; /** * Set the default URL credential to be set for request operations. */ @property (strong, nonatomic, nullable) NSURLCredential *urlCredential; /** * Set username */ @property (strong, nonatomic, nullable) NSString *username; /** * Set password */ @property (strong, nonatomic, nullable) NSString *password; /** * Set filter to pick headers for downloading image HTTP request. * * This block will be invoked for each downloading image request, returned * NSDictionary will be used as headers in corresponding HTTP request. */ @property (nonatomic, copy, nullable) SDWebImageDownloaderHeadersFilterBlock headersFilter; /** * Creates an instance of a downloader with specified session configuration. * *Note*: `timeoutIntervalForRequest` is going to be overwritten. * @return new instance of downloader class */ - (nonnull instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)sessionConfiguration NS_DESIGNATED_INITIALIZER; /** * Set a value for a HTTP header to be appended to each download HTTP request. * * @param value The value for the header field. Use `nil` value to remove the header. * @param field The name of the header field to set. */ - (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)field; /** * Returns the value of the specified HTTP header field. * * @return The value associated with the header field field, or `nil` if there is no corresponding header field. */ - (nullable NSString *)valueForHTTPHeaderField:(nullable NSString *)field; /** * Sets a subclass of `SDWebImageDownloaderOperation` as the default * `NSOperation` to be used each time SDWebImage constructs a request * operation to download an image. * * @param operationClass The subclass of `SDWebImageDownloaderOperation` to set * as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`. */ - (void)setOperationClass:(nullable Class)operationClass; /** * Creates a SDWebImageDownloader async downloader instance with a given URL * * The delegate will be informed when the image is finish downloaded or an error has happen. * * @see SDWebImageDownloaderDelegate * * @param url The URL to the image to download * @param options The options to be used for this download * @param progressBlock A block called repeatedly while the image is downloading * @note the progress block is executed on a background queue * @param completedBlock A block called once the download is completed. * If the download succeeded, the image parameter is set, in case of error, * error parameter is set with the error. The last parameter is always YES * if SDWebImageDownloaderProgressiveDownload isn't use. With the * SDWebImageDownloaderProgressiveDownload option, this block is called * repeatedly with the partial image object and the finished argument set to NO * before to be called a last time with the full image and finished argument * set to YES. In case of error, the finished argument is always YES. * * @return A token (SDWebImageDownloadToken) that can be passed to -cancel: to cancel this operation */ - (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; /** * Cancels a download that was previously queued using -downloadImageWithURL:options:progress:completed: * * @param token The token received from -downloadImageWithURL:options:progress:completed: that should be canceled. */ - (void)cancel:(nullable SDWebImageDownloadToken *)token; /** * Sets the download queue suspension state */ - (void)setSuspended:(BOOL)suspended; /** * Cancels all download operations in the queue */ - (void)cancelAllDownloads; @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/SDWebImageDownloader.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,774
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * (c) james <path_to_url * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageDecoder.h" @implementation UIImage (ForceDecode) #if SD_UIKIT || SD_WATCH static const size_t kBytesPerPixel = 4; static const size_t kBitsPerComponent = 8; + (nullable UIImage *)decodedImageWithImage:(nullable UIImage *)image { if (![UIImage shouldDecodeImage:image]) { return image; } // autorelease the bitmap context and all vars to help system to free memory when there are memory warning. // on iOS7, do not forget to call [[SDImageCache sharedImageCache] clearMemory]; @autoreleasepool{ CGImageRef imageRef = image.CGImage; CGColorSpaceRef colorspaceRef = [UIImage colorSpaceForImageRef:imageRef]; size_t width = CGImageGetWidth(imageRef); size_t height = CGImageGetHeight(imageRef); size_t bytesPerRow = kBytesPerPixel * width; // kCGImageAlphaNone is not supported in CGBitmapContextCreate. // Since the original image here has no alpha info, use kCGImageAlphaNoneSkipLast // to create bitmap graphics contexts without alpha info. CGContextRef context = CGBitmapContextCreate(NULL, width, height, kBitsPerComponent, bytesPerRow, colorspaceRef, kCGBitmapByteOrderDefault|kCGImageAlphaNoneSkipLast); if (context == NULL) { return image; } // Draw the image into the context and retrieve the new bitmap image without alpha CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); CGImageRef imageRefWithoutAlpha = CGBitmapContextCreateImage(context); UIImage *imageWithoutAlpha = [UIImage imageWithCGImage:imageRefWithoutAlpha scale:image.scale orientation:image.imageOrientation]; CGContextRelease(context); CGImageRelease(imageRefWithoutAlpha); return imageWithoutAlpha; } } /* * Defines the maximum size in MB of the decoded image when the flag `SDWebImageScaleDownLargeImages` is set * Suggested value for iPad1 and iPhone 3GS: 60. * Suggested value for iPad2 and iPhone 4: 120. * Suggested value for iPhone 3G and iPod 2 and earlier devices: 30. */ static const CGFloat kDestImageSizeMB = 60.0f; /* * Defines the maximum size in MB of a tile used to decode image when the flag `SDWebImageScaleDownLargeImages` is set * Suggested value for iPad1 and iPhone 3GS: 20. * Suggested value for iPad2 and iPhone 4: 40. * Suggested value for iPhone 3G and iPod 2 and earlier devices: 10. */ static const CGFloat kSourceImageTileSizeMB = 20.0f; static const CGFloat kBytesPerMB = 1024.0f * 1024.0f; static const CGFloat kPixelsPerMB = kBytesPerMB / kBytesPerPixel; static const CGFloat kDestTotalPixels = kDestImageSizeMB * kPixelsPerMB; static const CGFloat kTileTotalPixels = kSourceImageTileSizeMB * kPixelsPerMB; static const CGFloat kDestSeemOverlap = 2.0f; // the numbers of pixels to overlap the seems where tiles meet. + (nullable UIImage *)decodedAndScaledDownImageWithImage:(nullable UIImage *)image { if (![UIImage shouldDecodeImage:image]) { return image; } if (![UIImage shouldScaleDownImage:image]) { return [UIImage decodedImageWithImage:image]; } CGContextRef destContext; // autorelease the bitmap context and all vars to help system to free memory when there are memory warning. // on iOS7, do not forget to call [[SDImageCache sharedImageCache] clearMemory]; @autoreleasepool { CGImageRef sourceImageRef = image.CGImage; CGSize sourceResolution = CGSizeZero; sourceResolution.width = CGImageGetWidth(sourceImageRef); sourceResolution.height = CGImageGetHeight(sourceImageRef); float sourceTotalPixels = sourceResolution.width * sourceResolution.height; // Determine the scale ratio to apply to the input image // that results in an output image of the defined size. // see kDestImageSizeMB, and how it relates to destTotalPixels. float imageScale = kDestTotalPixels / sourceTotalPixels; CGSize destResolution = CGSizeZero; destResolution.width = (int)(sourceResolution.width*imageScale); destResolution.height = (int)(sourceResolution.height*imageScale); // current color space CGColorSpaceRef colorspaceRef = [UIImage colorSpaceForImageRef:sourceImageRef]; size_t bytesPerRow = kBytesPerPixel * destResolution.width; // Allocate enough pixel data to hold the output image. void* destBitmapData = malloc( bytesPerRow * destResolution.height ); if (destBitmapData == NULL) { return image; } // kCGImageAlphaNone is not supported in CGBitmapContextCreate. // Since the original image here has no alpha info, use kCGImageAlphaNoneSkipLast // to create bitmap graphics contexts without alpha info. destContext = CGBitmapContextCreate(destBitmapData, destResolution.width, destResolution.height, kBitsPerComponent, bytesPerRow, colorspaceRef, kCGBitmapByteOrderDefault|kCGImageAlphaNoneSkipLast); if (destContext == NULL) { free(destBitmapData); return image; } CGContextSetInterpolationQuality(destContext, kCGInterpolationHigh); // Now define the size of the rectangle to be used for the // incremental blits from the input image to the output image. // we use a source tile width equal to the width of the source // image due to the way that iOS retrieves image data from disk. // iOS must decode an image from disk in full width 'bands', even // if current graphics context is clipped to a subrect within that // band. Therefore we fully utilize all of the pixel data that results // from a decoding opertion by achnoring our tile size to the full // width of the input image. CGRect sourceTile = CGRectZero; sourceTile.size.width = sourceResolution.width; // The source tile height is dynamic. Since we specified the size // of the source tile in MB, see how many rows of pixels high it // can be given the input image width. sourceTile.size.height = (int)(kTileTotalPixels / sourceTile.size.width ); sourceTile.origin.x = 0.0f; // The output tile is the same proportions as the input tile, but // scaled to image scale. CGRect destTile; destTile.size.width = destResolution.width; destTile.size.height = sourceTile.size.height * imageScale; destTile.origin.x = 0.0f; // The source seem overlap is proportionate to the destination seem overlap. // this is the amount of pixels to overlap each tile as we assemble the ouput image. float sourceSeemOverlap = (int)((kDestSeemOverlap/destResolution.height)*sourceResolution.height); CGImageRef sourceTileImageRef; // calculate the number of read/write operations required to assemble the // output image. int iterations = (int)( sourceResolution.height / sourceTile.size.height ); // If tile height doesn't divide the image height evenly, add another iteration // to account for the remaining pixels. int remainder = (int)sourceResolution.height % (int)sourceTile.size.height; if(remainder) { iterations++; } // Add seem overlaps to the tiles, but save the original tile height for y coordinate calculations. float sourceTileHeightMinusOverlap = sourceTile.size.height; sourceTile.size.height += sourceSeemOverlap; destTile.size.height += kDestSeemOverlap; for( int y = 0; y < iterations; ++y ) { @autoreleasepool { sourceTile.origin.y = y * sourceTileHeightMinusOverlap + sourceSeemOverlap; destTile.origin.y = destResolution.height - (( y + 1 ) * sourceTileHeightMinusOverlap * imageScale + kDestSeemOverlap); sourceTileImageRef = CGImageCreateWithImageInRect( sourceImageRef, sourceTile ); if( y == iterations - 1 && remainder ) { float dify = destTile.size.height; destTile.size.height = CGImageGetHeight( sourceTileImageRef ) * imageScale; dify -= destTile.size.height; destTile.origin.y += dify; } CGContextDrawImage( destContext, destTile, sourceTileImageRef ); CGImageRelease( sourceTileImageRef ); } } CGImageRef destImageRef = CGBitmapContextCreateImage(destContext); CGContextRelease(destContext); if (destImageRef == NULL) { return image; } UIImage *destImage = [UIImage imageWithCGImage:destImageRef scale:image.scale orientation:image.imageOrientation]; CGImageRelease(destImageRef); if (destImage == nil) { return image; } return destImage; } } + (BOOL)shouldDecodeImage:(nullable UIImage *)image { // Prevent "CGBitmapContextCreateImage: invalid context 0x0" error if (image == nil) { return NO; } // do not decode animated images if (image.images != nil) { return NO; } CGImageRef imageRef = image.CGImage; CGImageAlphaInfo alpha = CGImageGetAlphaInfo(imageRef); BOOL anyAlpha = (alpha == kCGImageAlphaFirst || alpha == kCGImageAlphaLast || alpha == kCGImageAlphaPremultipliedFirst || alpha == kCGImageAlphaPremultipliedLast); // do not decode images with alpha if (anyAlpha) { return NO; } return YES; } + (BOOL)shouldScaleDownImage:(nonnull UIImage *)image { BOOL shouldScaleDown = YES; CGImageRef sourceImageRef = image.CGImage; CGSize sourceResolution = CGSizeZero; sourceResolution.width = CGImageGetWidth(sourceImageRef); sourceResolution.height = CGImageGetHeight(sourceImageRef); float sourceTotalPixels = sourceResolution.width * sourceResolution.height; float imageScale = kDestTotalPixels / sourceTotalPixels; if (imageScale < 1) { shouldScaleDown = YES; } else { shouldScaleDown = NO; } return shouldScaleDown; } + (CGColorSpaceRef)colorSpaceForImageRef:(CGImageRef)imageRef { // current CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(CGImageGetColorSpace(imageRef)); CGColorSpaceRef colorspaceRef = CGImageGetColorSpace(imageRef); BOOL unsupportedColorSpace = (imageColorSpaceModel == kCGColorSpaceModelUnknown || imageColorSpaceModel == kCGColorSpaceModelMonochrome || imageColorSpaceModel == kCGColorSpaceModelCMYK || imageColorSpaceModel == kCGColorSpaceModelIndexed); if (unsupportedColorSpace) { colorspaceRef = CGColorSpaceCreateDeviceRGB(); CFAutorelease(colorspaceRef); } return colorspaceRef; } #elif SD_MAC + (nullable UIImage *)decodedImageWithImage:(nullable UIImage *)image { return image; } + (nullable UIImage *)decodedAndScaledDownImageWithImage:(nullable UIImage *)image { return image; } #endif @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/SDWebImageDecoder.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,586
```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" @interface SDWebImagePrefetcher () @property (strong, nonatomic, nonnull) SDWebImageManager *manager; @property (strong, nonatomic, nullable) NSArray<NSURL *> *prefetchURLs; @property (assign, nonatomic) NSUInteger requestedCount; @property (assign, nonatomic) NSUInteger skippedCount; @property (assign, nonatomic) NSUInteger finishedCount; @property (assign, nonatomic) NSTimeInterval startedTime; @property (copy, nonatomic, nullable) SDWebImagePrefetcherCompletionBlock completionBlock; @property (copy, nonatomic, nullable) SDWebImagePrefetcherProgressBlock progressBlock; @end @implementation SDWebImagePrefetcher + (nonnull instancetype)sharedImagePrefetcher { static dispatch_once_t once; static id instance; dispatch_once(&once, ^{ instance = [self new]; }); return instance; } - (nonnull instancetype)init { return [self initWithImageManager:[SDWebImageManager new]]; } - (nonnull instancetype)initWithImageManager:(SDWebImageManager *)manager { if ((self = [super init])) { _manager = manager; _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 loadImageWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSData *data, 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); } } else { if (self.progressBlock) { self.progressBlock(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; } self.progressBlock = nil; } }]; } - (void)reportStatus { NSUInteger total = (self.prefetchURLs).count; if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) { [self.delegate imagePrefetcher:self didFinishWithTotalCount:(total - self.skippedCount) skippedCount:self.skippedCount ]; } } - (void)prefetchURLs:(nullable NSArray<NSURL *> *)urls { [self prefetchURLs:urls progress:nil completed:nil]; } - (void)prefetchURLs:(nullable NSArray<NSURL *> *)urls progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock completed:(nullable 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/Pods/SDWebImage/SDWebImage/SDWebImagePrefetcher.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,104
```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" #if SD_UIKIT || SD_MAC #import "SDWebImageManager.h" typedef void(^SDSetImageBlock)(UIImage * _Nullable image, NSData * _Nullable imageData); @interface UIView (WebCache) /** * Get the current image URL. * * Note that because of the limitations of categories this property can get out of sync * if you use setImage: directly. */ - (nullable NSURL *)sd_imageURL; /** * Set the imageView `image` with an `url` and optionally a 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 operationKey A string to be used as the operation key. If nil, will use the class name * @param setImageBlock Block used for custom set image code * @param progressBlock A block called while image is downloading * @note the progress block is executed on a background queue * @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 retrieved from the local cache or from the network. * The fourth parameter is the original image url. */ - (void)sd_internalSetImageWithURL:(nullable NSURL *)url placeholderImage:(nullable UIImage *)placeholder options:(SDWebImageOptions)options operationKey:(nullable NSString *)operationKey setImageBlock:(nullable SDSetImageBlock)setImageBlock progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock; /** * Cancel the current download */ - (void)sd_cancelCurrentImageLoad; #if SD_UIKIT #pragma mark - Activity indicator /** * Show activity UIActivityIndicatorView */ - (void)sd_setShowActivityIndicatorView:(BOOL)show; /** * set desired UIActivityIndicatorViewStyle * * @param style The style of the UIActivityIndicatorView */ - (void)sd_setIndicatorStyle:(UIActivityIndicatorViewStyle)style; - (BOOL)sd_showActivityIndicatorView; - (void)sd_addActivityIndicator; - (void)sd_removeActivityIndicator; #endif @end #endif ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/UIView+WebCache.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
591
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * (c) Laurin Brandner * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "UIImage+GIF.h" #import <ImageIO/ImageIO.h> #import "objc/runtime.h" #import "NSImage+WebCache.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 *staticImage; if (count <= 1) { staticImage = [[UIImage alloc] initWithData:data]; } else { // we will only retrieve the 1st frame. the full GIF support is available via the FLAnimatedImageView category. // this here is only code to allow drawing animated images as static ones #if SD_WATCH CGFloat scale = 1; scale = [WKInterfaceDevice currentDevice].screenScale; #elif SD_UIKIT CGFloat scale = 1; scale = [UIScreen mainScreen].scale; #endif CGImageRef CGImage = CGImageSourceCreateImageAtIndex(source, 0, NULL); #if SD_UIKIT || SD_WATCH UIImage *frameImage = [UIImage imageWithCGImage:CGImage scale:scale orientation:UIImageOrientationUp]; staticImage = [UIImage animatedImageWithImages:@[frameImage] duration:0.0f]; #elif SD_MAC staticImage = [[UIImage alloc] initWithCGImage:CGImage size:NSZeroSize]; #endif CGImageRelease(CGImage); } CFRelease(source); return staticImage; } - (BOOL)isGIF { return (self.images != nil); } @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/UIImage+GIF.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
419
```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+HighlightedWebCache.h" #if SD_UIKIT #import "UIView+WebCacheOperation.h" #import "UIView+WebCache.h" @implementation UIImageView (HighlightedWebCache) - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url { [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil]; } - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options { [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil]; } - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:completedBlock]; } - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options completed:(nullable SDExternalCompletionBlock)completedBlock { [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:completedBlock]; } - (void)sd_setHighlightedImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock completed:(nullable SDExternalCompletionBlock)completedBlock { __weak typeof(self)weakSelf = self; [self sd_internalSetImageWithURL:url placeholderImage:nil options:options operationKey:@"UIImageViewImageOperationHighlighted" setImageBlock:^(UIImage *image, NSData *imageData) { weakSelf.highlightedImage = image; } progress:progressBlock completed:completedBlock]; } @end #endif ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
396
```objective-c /* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <rs@dailymotion.com> * (c) Fabrice Aneche * * 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" typedef NS_ENUM(NSInteger, SDImageFormat) { SDImageFormatUndefined = -1, SDImageFormatJPEG = 0, SDImageFormatPNG, SDImageFormatGIF, SDImageFormatTIFF, SDImageFormatWebP }; @interface NSData (ImageContentType) /** * Return image format * * @param data the input image data * * @return the image format as `SDImageFormat` (enum) */ + (SDImageFormat)sd_imageFormatForImageData:(nullable NSData *)data; @end ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/NSData+ImageContentType.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
198
```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" #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 * _Nullable key, UIImage * _Nullable image) { if (!image) { return nil; } #if SD_MAC return image; #elif SD_UIKIT || SD_WATCH if ((image.images).count > 0) { NSMutableArray<UIImage *> *scaledImages = [NSMutableArray array]; for (UIImage *tempImage in image.images) { [scaledImages addObject:SDScaledImageForKey(key, tempImage)]; } return [UIImage animatedImageWithImages:scaledImages duration:image.duration]; } else { #if SD_WATCH if ([[WKInterfaceDevice currentDevice] respondsToSelector:@selector(screenScale)]) { #elif SD_UIKIT if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { #endif CGFloat scale = 1; if (key.length >= 8) { NSRange range = [key rangeOfString:@"@2x."]; if (range.location != NSNotFound) { scale = 2.0; } range = [key rangeOfString:@"@3x."]; if (range.location != NSNotFound) { scale = 3.0; } } UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; image = scaledImage; } return image; } #endif } NSString *const SDWebImageErrorDomain = @"SDWebImageErrorDomain"; ```
/content/code_sandbox/Pods/SDWebImage/SDWebImage/SDWebImageCompat.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
406
```objective-c // // WebViewJavascriptBridgeBase.m // // Created by @LokiMeyburg on 10/15/14. // #import <Foundation/Foundation.h> #import "WebViewJavascriptBridgeBase.h" #import "WebViewJavascriptBridge_JS.h" @implementation WebViewJavascriptBridgeBase { __weak id _webViewDelegate; long _uniqueId; } static bool logging = false; static int logMaxLength = 500; + (void)enableLogging { logging = true; } + (void)setLogMaxLength:(int)length { logMaxLength = length;} - (id)init { if (self = [super init]) { self.messageHandlers = [NSMutableDictionary dictionary]; self.startupMessageQueue = [NSMutableArray array]; self.responseCallbacks = [NSMutableDictionary dictionary]; _uniqueId = 0; } return self; } - (void)dealloc { self.startupMessageQueue = nil; self.responseCallbacks = nil; self.messageHandlers = nil; } - (void)reset { self.startupMessageQueue = [NSMutableArray array]; self.responseCallbacks = [NSMutableDictionary dictionary]; _uniqueId = 0; } - (void)sendData:(id)data responseCallback:(WVJBResponseCallback)responseCallback handlerName:(NSString*)handlerName { NSMutableDictionary* message = [NSMutableDictionary dictionary]; if (data) { message[@"data"] = data; } if (responseCallback) { NSString* callbackId = [NSString stringWithFormat:@"objc_cb_%ld", ++_uniqueId]; self.responseCallbacks[callbackId] = [responseCallback copy]; message[@"callbackId"] = callbackId; } if (handlerName) { message[@"handlerName"] = handlerName; } [self _queueMessage:message]; } - (void)flushMessageQueue:(NSString *)messageQueueString{ if (messageQueueString == nil || messageQueueString.length == 0) { NSLog(@"WebViewJavascriptBridge: WARNING: ObjC got nil while fetching the message queue JSON from webview. This can happen if the WebViewJavascriptBridge JS is not currently present in the webview, e.g if the webview just loaded a new page."); return; } id messages = [self _deserializeMessageJSON:messageQueueString]; for (WVJBMessage* message in messages) { if (![message isKindOfClass:[WVJBMessage class]]) { NSLog(@"WebViewJavascriptBridge: WARNING: Invalid %@ received: %@", [message class], message); continue; } [self _log:@"RCVD" json:message]; NSString* responseId = message[@"responseId"]; if (responseId) { WVJBResponseCallback responseCallback = _responseCallbacks[responseId]; responseCallback(message[@"responseData"]); [self.responseCallbacks removeObjectForKey:responseId]; } else { WVJBResponseCallback responseCallback = NULL; NSString* callbackId = message[@"callbackId"]; if (callbackId) { responseCallback = ^(id responseData) { if (responseData == nil) { responseData = [NSNull null]; } WVJBMessage* msg = @{ @"responseId":callbackId, @"responseData":responseData }; [self _queueMessage:msg]; }; } else { responseCallback = ^(id ignoreResponseData) { // Do nothing }; } WVJBHandler handler = self.messageHandlers[message[@"handlerName"]]; if (!handler) { NSLog(@"WVJBNoHandlerException, No handler for message from JS: %@", message); continue; } handler(message[@"data"], responseCallback); } } } - (void)injectJavascriptFile { NSString *js = WebViewJavascriptBridge_js(); [self _evaluateJavascript:js]; if (self.startupMessageQueue) { NSArray* queue = self.startupMessageQueue; self.startupMessageQueue = nil; for (id queuedMessage in queue) { [self _dispatchMessage:queuedMessage]; } } } - (BOOL)isWebViewJavascriptBridgeURL:(NSURL*)url { if (![self isSchemeMatch:url]) { return NO; } return [self isBridgeLoadedURL:url] || [self isQueueMessageURL:url]; } - (BOOL)isSchemeMatch:(NSURL*)url { NSString* scheme = url.scheme.lowercaseString; return [scheme isEqualToString:kNewProtocolScheme] || [scheme isEqualToString:kOldProtocolScheme]; } - (BOOL)isQueueMessageURL:(NSURL*)url { NSString* host = url.host.lowercaseString; return [self isSchemeMatch:url] && [host isEqualToString:kQueueHasMessage]; } - (BOOL)isBridgeLoadedURL:(NSURL*)url { NSString* host = url.host.lowercaseString; return [self isSchemeMatch:url] && [host isEqualToString:kBridgeLoaded]; } - (void)logUnkownMessage:(NSURL*)url { NSLog(@"WebViewJavascriptBridge: WARNING: Received unknown WebViewJavascriptBridge command %@", [url absoluteString]); } - (NSString *)webViewJavascriptCheckCommand { return @"typeof WebViewJavascriptBridge == \'object\';"; } - (NSString *)webViewJavascriptFetchQueyCommand { return @"WebViewJavascriptBridge._fetchQueue();"; } - (void)disableJavscriptAlertBoxSafetyTimeout { [self sendData:nil responseCallback:nil handlerName:@"_disableJavascriptAlertBoxSafetyTimeout"]; } // Private // ------------------------------------------- - (void) _evaluateJavascript:(NSString *)javascriptCommand { [self.delegate _evaluateJavascript:javascriptCommand]; } - (void)_queueMessage:(WVJBMessage*)message { if (self.startupMessageQueue) { [self.startupMessageQueue addObject:message]; } else { [self _dispatchMessage:message]; } } - (void)_dispatchMessage:(WVJBMessage*)message { NSString *messageJSON = [self _serializeMessage:message pretty:NO]; [self _log:@"SEND" json:messageJSON]; messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"]; messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""]; messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\'" withString:@"\\\'"]; messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"]; messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\r" withString:@"\\r"]; messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\f" withString:@"\\f"]; messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\u2028" withString:@"\\u2028"]; messageJSON = [messageJSON stringByReplacingOccurrencesOfString:@"\u2029" withString:@"\\u2029"]; NSString* javascriptCommand = [NSString stringWithFormat:@"WebViewJavascriptBridge._handleMessageFromObjC('%@');", messageJSON]; if ([[NSThread currentThread] isMainThread]) { [self _evaluateJavascript:javascriptCommand]; } else { dispatch_sync(dispatch_get_main_queue(), ^{ [self _evaluateJavascript:javascriptCommand]; }); } } - (NSString *)_serializeMessage:(id)message pretty:(BOOL)pretty{ return [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:message options:(NSJSONWritingOptions)(pretty ? NSJSONWritingPrettyPrinted : 0) error:nil] encoding:NSUTF8StringEncoding]; } - (NSArray*)_deserializeMessageJSON:(NSString *)messageJSON { return [NSJSONSerialization JSONObjectWithData:[messageJSON dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil]; } - (void)_log:(NSString *)action json:(id)json { if (!logging) { return; } if (![json isKindOfClass:[NSString class]]) { json = [self _serializeMessage:json pretty:YES]; } if ([json length] > logMaxLength) { NSLog(@"WVJB %@: %@ [...]", action, [json substringToIndex:logMaxLength]); } else { NSLog(@"WVJB %@: %@", action, json); } } @end ```
/content/code_sandbox/Pods/WebViewJavascriptBridge/WebViewJavascriptBridge/WebViewJavascriptBridgeBase.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,713
```objective-c // This file contains the source for the Javascript side of the // WebViewJavascriptBridge. It is plaintext, but converted to an NSString // via some preprocessor tricks. // // Previous implementations of WebViewJavascriptBridge loaded the javascript source // from a resource. This worked fine for app developers, but library developers who // included the bridge into their library, awkwardly had to ask consumers of their // library to include the resource, violating their encapsulation. By including the // Javascript as a string resource, the encapsulation of the library is maintained. #import "WebViewJavascriptBridge_JS.h" NSString * WebViewJavascriptBridge_js() { #define __wvjb_js_func__(x) #x // BEGIN preprocessorJSCode static NSString * preprocessorJSCode = @__wvjb_js_func__( ;(function() { if (window.WebViewJavascriptBridge) { return; } if (!window.onerror) { window.onerror = function(msg, url, line) { console.log("WebViewJavascriptBridge: ERROR:" + msg + "@" + url + ":" + line); } } window.WebViewJavascriptBridge = { registerHandler: registerHandler, callHandler: callHandler, disableJavscriptAlertBoxSafetyTimeout: disableJavscriptAlertBoxSafetyTimeout, _fetchQueue: _fetchQueue, _handleMessageFromObjC: _handleMessageFromObjC }; var messagingIframe; var sendMessageQueue = []; var messageHandlers = {}; var CUSTOM_PROTOCOL_SCHEME = 'https'; var QUEUE_HAS_MESSAGE = '__wvjb_queue_message__'; var responseCallbacks = {}; var uniqueId = 1; var dispatchMessagesWithTimeoutSafety = true; function registerHandler(handlerName, handler) { messageHandlers[handlerName] = handler; } function callHandler(handlerName, data, responseCallback) { if (arguments.length == 2 && typeof data == 'function') { responseCallback = data; data = null; } _doSend({ handlerName:handlerName, data:data }, responseCallback); } function disableJavscriptAlertBoxSafetyTimeout() { dispatchMessagesWithTimeoutSafety = false; } function _doSend(message, responseCallback) { if (responseCallback) { var callbackId = 'cb_'+(uniqueId++)+'_'+new Date().getTime(); responseCallbacks[callbackId] = responseCallback; message['callbackId'] = callbackId; } sendMessageQueue.push(message); messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE; } function _fetchQueue() { var messageQueueString = JSON.stringify(sendMessageQueue); sendMessageQueue = []; return messageQueueString; } function _dispatchMessageFromObjC(messageJSON) { if (dispatchMessagesWithTimeoutSafety) { setTimeout(_doDispatchMessageFromObjC); } else { _doDispatchMessageFromObjC(); } function _doDispatchMessageFromObjC() { var message = JSON.parse(messageJSON); var messageHandler; var responseCallback; if (message.responseId) { responseCallback = responseCallbacks[message.responseId]; if (!responseCallback) { return; } responseCallback(message.responseData); delete responseCallbacks[message.responseId]; } else { if (message.callbackId) { var callbackResponseId = message.callbackId; responseCallback = function(responseData) { _doSend({ handlerName:message.handlerName, responseId:callbackResponseId, responseData:responseData }); }; } var handler = messageHandlers[message.handlerName]; if (!handler) { console.log("WebViewJavascriptBridge: WARNING: no handler for message from ObjC:", message); } else { handler(message.data, responseCallback); } } } } function _handleMessageFromObjC(messageJSON) { _dispatchMessageFromObjC(messageJSON); } messagingIframe = document.createElement('iframe'); messagingIframe.style.display = 'none'; messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + '://' + QUEUE_HAS_MESSAGE; document.documentElement.appendChild(messagingIframe); registerHandler("_disableJavascriptAlertBoxSafetyTimeout", disableJavscriptAlertBoxSafetyTimeout); setTimeout(_callWVJBCallbacks, 0); function _callWVJBCallbacks() { var callbacks = window.WVJBCallbacks; delete window.WVJBCallbacks; for (var i=0; i<callbacks.length; i++) { callbacks[i](WebViewJavascriptBridge); } } })(); ); // END preprocessorJSCode #undef __wvjb_js_func__ return preprocessorJSCode; }; ```
/content/code_sandbox/Pods/WebViewJavascriptBridge/WebViewJavascriptBridge/WebViewJavascriptBridge_JS.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,025
```objective-c // // WKWebViewJavascriptBridge.h // // Created by @LokiMeyburg on 10/15/14. // #if (__MAC_OS_X_VERSION_MAX_ALLOWED > __MAC_10_9 || __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_1) #define supportsWKWebView #endif #if defined supportsWKWebView #import <Foundation/Foundation.h> #import "WebViewJavascriptBridgeBase.h" #import <WebKit/WebKit.h> @interface WKWebViewJavascriptBridge : NSObject<WKNavigationDelegate, WebViewJavascriptBridgeBaseDelegate> + (instancetype)bridgeForWebView:(WKWebView*)webView API_AVAILABLE(ios(8.0)); + (void)enableLogging; - (void)registerHandler:(NSString*)handlerName handler:(WVJBHandler)handler; - (void)removeHandler:(NSString*)handlerName; - (void)callHandler:(NSString*)handlerName; - (void)callHandler:(NSString*)handlerName data:(id)data; - (void)callHandler:(NSString*)handlerName data:(id)data responseCallback:(WVJBResponseCallback)responseCallback; - (void)reset; - (void)setWebViewDelegate:(id)webViewDelegate; - (void)disableJavscriptAlertBoxSafetyTimeout; @end #endif ```
/content/code_sandbox/Pods/WebViewJavascriptBridge/WebViewJavascriptBridge/WKWebViewJavascriptBridge.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
264
```objective-c #import <Foundation/Foundation.h> NSString * WebViewJavascriptBridge_js(void); ```
/content/code_sandbox/Pods/WebViewJavascriptBridge/WebViewJavascriptBridge/WebViewJavascriptBridge_JS.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
15
```objective-c // // WebViewJavascriptBridge.m // ExampleApp-iOS // // Created by Marcus Westin on 6/14/13. // #import "WebViewJavascriptBridge.h" #if defined(supportsWKWebView) #import "WKWebViewJavascriptBridge.h" #endif #if __has_feature(objc_arc_weak) #define WVJB_WEAK __weak #else #define WVJB_WEAK __unsafe_unretained #endif @implementation WebViewJavascriptBridge { WVJB_WEAK WVJB_WEBVIEW_TYPE* _webView; WVJB_WEAK id _webViewDelegate; long _uniqueId; WebViewJavascriptBridgeBase *_base; } /* API *****/ + (void)enableLogging { [WebViewJavascriptBridgeBase enableLogging]; } + (void)setLogMaxLength:(int)length { [WebViewJavascriptBridgeBase setLogMaxLength:length]; } + (instancetype)bridgeForWebView:(id)webView { return [self bridge:webView]; } + (instancetype)bridge:(id)webView { #if defined supportsWKWebView if ([webView isKindOfClass:[WKWebView class]]) { return (WebViewJavascriptBridge*) [WKWebViewJavascriptBridge bridgeForWebView:webView]; } #endif if ([webView isKindOfClass:[WVJB_WEBVIEW_TYPE class]]) { WebViewJavascriptBridge* bridge = [[self alloc] init]; [bridge _platformSpecificSetup:webView]; return bridge; } [NSException raise:@"BadWebViewType" format:@"Unknown web view type."]; return nil; } - (void)setWebViewDelegate:(WVJB_WEBVIEW_DELEGATE_TYPE*)webViewDelegate { _webViewDelegate = webViewDelegate; } - (void)send:(id)data { [self send:data responseCallback:nil]; } - (void)send:(id)data responseCallback:(WVJBResponseCallback)responseCallback { [_base sendData:data responseCallback:responseCallback handlerName:nil]; } - (void)callHandler:(NSString *)handlerName { [self callHandler:handlerName data:nil responseCallback:nil]; } - (void)callHandler:(NSString *)handlerName data:(id)data { [self callHandler:handlerName data:data responseCallback:nil]; } - (void)callHandler:(NSString *)handlerName data:(id)data responseCallback:(WVJBResponseCallback)responseCallback { [_base sendData:data responseCallback:responseCallback handlerName:handlerName]; } - (void)registerHandler:(NSString *)handlerName handler:(WVJBHandler)handler { _base.messageHandlers[handlerName] = [handler copy]; } - (void)removeHandler:(NSString *)handlerName { [_base.messageHandlers removeObjectForKey:handlerName]; } - (void)disableJavscriptAlertBoxSafetyTimeout { [_base disableJavscriptAlertBoxSafetyTimeout]; } /* Platform agnostic internals *****************************/ - (void)dealloc { [self _platformSpecificDealloc]; _base = nil; _webView = nil; _webViewDelegate = nil; } - (NSString*) _evaluateJavascript:(NSString*)javascriptCommand { return [_webView stringByEvaluatingJavaScriptFromString:javascriptCommand]; } #if defined WVJB_PLATFORM_OSX /* Platform specific internals: OSX **********************************/ - (void) _platformSpecificSetup:(WVJB_WEBVIEW_TYPE*)webView { _webView = webView; _webView.policyDelegate = self; _base = [[WebViewJavascriptBridgeBase alloc] init]; _base.delegate = self; } - (void) _platformSpecificDealloc { _webView.policyDelegate = nil; } - (void)webView:(WebView *)webView decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener { if (webView != _webView) { return; } NSURL *url = [request URL]; if ([_base isWebViewJavascriptBridgeURL:url]) { if ([_base isBridgeLoadedURL:url]) { [_base injectJavascriptFile]; } else if ([_base isQueueMessageURL:url]) { NSString *messageQueueString = [self _evaluateJavascript:[_base webViewJavascriptFetchQueyCommand]]; [_base flushMessageQueue:messageQueueString]; } else { [_base logUnkownMessage:url]; } [listener ignore]; } else if (_webViewDelegate && [_webViewDelegate respondsToSelector:@selector(webView:decidePolicyForNavigationAction:request:frame:decisionListener:)]) { [_webViewDelegate webView:webView decidePolicyForNavigationAction:actionInformation request:request frame:frame decisionListener:listener]; } else { [listener use]; } } #elif defined WVJB_PLATFORM_IOS /* Platform specific internals: iOS **********************************/ - (void) _platformSpecificSetup:(WVJB_WEBVIEW_TYPE*)webView { _webView = webView; _webView.delegate = self; _base = [[WebViewJavascriptBridgeBase alloc] init]; _base.delegate = self; } - (void) _platformSpecificDealloc { _webView.delegate = nil; } - (void)webViewDidFinishLoad:(UIWebView *)webView { if (webView != _webView) { return; } __strong WVJB_WEBVIEW_DELEGATE_TYPE* strongDelegate = _webViewDelegate; if (strongDelegate && [strongDelegate respondsToSelector:@selector(webViewDidFinishLoad:)]) { [strongDelegate webViewDidFinishLoad:webView]; } } - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { if (webView != _webView) { return; } __strong WVJB_WEBVIEW_DELEGATE_TYPE* strongDelegate = _webViewDelegate; if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:didFailLoadWithError:)]) { [strongDelegate webView:webView didFailLoadWithError:error]; } } - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if (webView != _webView) { return YES; } NSURL *url = [request URL]; __strong WVJB_WEBVIEW_DELEGATE_TYPE* strongDelegate = _webViewDelegate; if ([_base isWebViewJavascriptBridgeURL:url]) { if ([_base isBridgeLoadedURL:url]) { [_base injectJavascriptFile]; } else if ([_base isQueueMessageURL:url]) { NSString *messageQueueString = [self _evaluateJavascript:[_base webViewJavascriptFetchQueyCommand]]; [_base flushMessageQueue:messageQueueString]; } else { [_base logUnkownMessage:url]; } return NO; } else if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]) { return [strongDelegate webView:webView shouldStartLoadWithRequest:request navigationType:navigationType]; } else { return YES; } } - (void)webViewDidStartLoad:(UIWebView *)webView { if (webView != _webView) { return; } __strong WVJB_WEBVIEW_DELEGATE_TYPE* strongDelegate = _webViewDelegate; if (strongDelegate && [strongDelegate respondsToSelector:@selector(webViewDidStartLoad:)]) { [strongDelegate webViewDidStartLoad:webView]; } } #endif @end ```
/content/code_sandbox/Pods/WebViewJavascriptBridge/WebViewJavascriptBridge/WebViewJavascriptBridge.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,545
```objective-c // // WebViewJavascriptBridge.h // ExampleApp-iOS // // Created by Marcus Westin on 6/14/13. // #import <Foundation/Foundation.h> #import "WebViewJavascriptBridgeBase.h" #if (__MAC_OS_X_VERSION_MAX_ALLOWED > __MAC_10_9 || __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_1) #define supportsWKWebView #endif #if defined supportsWKWebView #import <WebKit/WebKit.h> #endif #if defined __MAC_OS_X_VERSION_MAX_ALLOWED #define WVJB_PLATFORM_OSX #define WVJB_WEBVIEW_TYPE WebView #define WVJB_WEBVIEW_DELEGATE_TYPE NSObject<WebViewJavascriptBridgeBaseDelegate> #define WVJB_WEBVIEW_DELEGATE_INTERFACE NSObject<WebViewJavascriptBridgeBaseDelegate, WebPolicyDelegate> #elif defined __IPHONE_OS_VERSION_MAX_ALLOWED #import <UIKit/UIWebView.h> #define WVJB_PLATFORM_IOS #define WVJB_WEBVIEW_TYPE UIWebView #define WVJB_WEBVIEW_DELEGATE_TYPE NSObject<UIWebViewDelegate> #define WVJB_WEBVIEW_DELEGATE_INTERFACE NSObject<UIWebViewDelegate, WebViewJavascriptBridgeBaseDelegate> #endif @interface WebViewJavascriptBridge : WVJB_WEBVIEW_DELEGATE_INTERFACE + (instancetype)bridgeForWebView:(id)webView; + (instancetype)bridge:(id)webView; + (void)enableLogging; + (void)setLogMaxLength:(int)length; - (void)registerHandler:(NSString*)handlerName handler:(WVJBHandler)handler; - (void)removeHandler:(NSString*)handlerName; - (void)callHandler:(NSString*)handlerName; - (void)callHandler:(NSString*)handlerName data:(id)data; - (void)callHandler:(NSString*)handlerName data:(id)data responseCallback:(WVJBResponseCallback)responseCallback; - (void)setWebViewDelegate:(id)webViewDelegate; - (void)disableJavscriptAlertBoxSafetyTimeout; @end ```
/content/code_sandbox/Pods/WebViewJavascriptBridge/WebViewJavascriptBridge/WebViewJavascriptBridge.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
420
```objective-c // // WebViewJavascriptBridgeBase.h // // Created by @LokiMeyburg on 10/15/14. // #import <Foundation/Foundation.h> #define kOldProtocolScheme @"wvjbscheme" #define kNewProtocolScheme @"https" #define kQueueHasMessage @"__wvjb_queue_message__" #define kBridgeLoaded @"__bridge_loaded__" typedef void (^WVJBResponseCallback)(id responseData); typedef void (^WVJBHandler)(id data, WVJBResponseCallback responseCallback); typedef NSDictionary WVJBMessage; @protocol WebViewJavascriptBridgeBaseDelegate <NSObject> - (NSString*) _evaluateJavascript:(NSString*)javascriptCommand; @end @interface WebViewJavascriptBridgeBase : NSObject @property (weak, nonatomic) id <WebViewJavascriptBridgeBaseDelegate> delegate; @property (strong, nonatomic) NSMutableArray* startupMessageQueue; @property (strong, nonatomic) NSMutableDictionary* responseCallbacks; @property (strong, nonatomic) NSMutableDictionary* messageHandlers; @property (strong, nonatomic) WVJBHandler messageHandler; + (void)enableLogging; + (void)setLogMaxLength:(int)length; - (void)reset; - (void)sendData:(id)data responseCallback:(WVJBResponseCallback)responseCallback handlerName:(NSString*)handlerName; - (void)flushMessageQueue:(NSString *)messageQueueString; - (void)injectJavascriptFile; - (BOOL)isWebViewJavascriptBridgeURL:(NSURL*)url; - (BOOL)isQueueMessageURL:(NSURL*)urll; - (BOOL)isBridgeLoadedURL:(NSURL*)urll; - (void)logUnkownMessage:(NSURL*)url; - (NSString *)webViewJavascriptCheckCommand; - (NSString *)webViewJavascriptFetchQueyCommand; - (void)disableJavscriptAlertBoxSafetyTimeout; @end ```
/content/code_sandbox/Pods/WebViewJavascriptBridge/WebViewJavascriptBridge/WebViewJavascriptBridgeBase.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
376
```objective-c // // WKWebViewJavascriptBridge.m // // Created by @LokiMeyburg on 10/15/14. // #import "WKWebViewJavascriptBridge.h" #if defined supportsWKWebView @implementation WKWebViewJavascriptBridge { __weak WKWebView* _webView; __weak id<WKNavigationDelegate> _webViewDelegate; long _uniqueId; WebViewJavascriptBridgeBase *_base; } /* API *****/ + (void)enableLogging { [WebViewJavascriptBridgeBase enableLogging]; } + (instancetype)bridgeForWebView:(WKWebView*)webView { WKWebViewJavascriptBridge* bridge = [[self alloc] init]; [bridge _setupInstance:webView]; [bridge reset]; return bridge; } - (void)send:(id)data { [self send:data responseCallback:nil]; } - (void)send:(id)data responseCallback:(WVJBResponseCallback)responseCallback { [_base sendData:data responseCallback:responseCallback handlerName:nil]; } - (void)callHandler:(NSString *)handlerName { [self callHandler:handlerName data:nil responseCallback:nil]; } - (void)callHandler:(NSString *)handlerName data:(id)data { [self callHandler:handlerName data:data responseCallback:nil]; } - (void)callHandler:(NSString *)handlerName data:(id)data responseCallback:(WVJBResponseCallback)responseCallback { [_base sendData:data responseCallback:responseCallback handlerName:handlerName]; } - (void)registerHandler:(NSString *)handlerName handler:(WVJBHandler)handler { _base.messageHandlers[handlerName] = [handler copy]; } - (void)removeHandler:(NSString *)handlerName { [_base.messageHandlers removeObjectForKey:handlerName]; } - (void)reset { [_base reset]; } - (void)setWebViewDelegate:(id<WKNavigationDelegate>)webViewDelegate { _webViewDelegate = webViewDelegate; } - (void)disableJavscriptAlertBoxSafetyTimeout { [_base disableJavscriptAlertBoxSafetyTimeout]; } /* Internals ***********/ - (void)dealloc { _base = nil; _webView = nil; _webViewDelegate = nil; _webView.navigationDelegate = nil; } /* WKWebView Specific Internals ******************************/ - (void) _setupInstance:(WKWebView*)webView { _webView = webView; _webView.navigationDelegate = self; _base = [[WebViewJavascriptBridgeBase alloc] init]; _base.delegate = self; } - (void)WKFlushMessageQueue { [_webView evaluateJavaScript:[_base webViewJavascriptFetchQueyCommand] completionHandler:^(NSString* result, NSError* error) { if (error != nil) { NSLog(@"WebViewJavascriptBridge: WARNING: Error when trying to fetch data from WKWebView: %@", error); } [_base flushMessageQueue:result]; }]; } - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { if (webView != _webView) { return; } __strong typeof(_webViewDelegate) strongDelegate = _webViewDelegate; if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:didFinishNavigation:)]) { [strongDelegate webView:webView didFinishNavigation:navigation]; } } - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler { if (webView != _webView) { return; } __strong typeof(_webViewDelegate) strongDelegate = _webViewDelegate; if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:decidePolicyForNavigationResponse:decisionHandler:)]) { [strongDelegate webView:webView decidePolicyForNavigationResponse:navigationResponse decisionHandler:decisionHandler]; } else { decisionHandler(WKNavigationResponsePolicyAllow); } } - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler { if (webView != _webView) { return; } __strong typeof(_webViewDelegate) strongDelegate = _webViewDelegate; if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:didReceiveAuthenticationChallenge:completionHandler:)]) { [strongDelegate webView:webView didReceiveAuthenticationChallenge:challenge completionHandler:completionHandler]; } else { completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil); } } - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { if (webView != _webView) { return; } NSURL *url = navigationAction.request.URL; __strong typeof(_webViewDelegate) strongDelegate = _webViewDelegate; if ([_base isWebViewJavascriptBridgeURL:url]) { if ([_base isBridgeLoadedURL:url]) { [_base injectJavascriptFile]; } else if ([_base isQueueMessageURL:url]) { [self WKFlushMessageQueue]; } else { [_base logUnkownMessage:url]; } decisionHandler(WKNavigationActionPolicyCancel); return; } if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:decidePolicyForNavigationAction:decisionHandler:)]) { [_webViewDelegate webView:webView decidePolicyForNavigationAction:navigationAction decisionHandler:decisionHandler]; } else { decisionHandler(WKNavigationActionPolicyAllow); } } - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation { if (webView != _webView) { return; } __strong typeof(_webViewDelegate) strongDelegate = _webViewDelegate; if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:didStartProvisionalNavigation:)]) { [strongDelegate webView:webView didStartProvisionalNavigation:navigation]; } } - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error { if (webView != _webView) { return; } __strong typeof(_webViewDelegate) strongDelegate = _webViewDelegate; if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:didFailNavigation:withError:)]) { [strongDelegate webView:webView didFailNavigation:navigation withError:error]; } } - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error { if (webView != _webView) { return; } __strong typeof(_webViewDelegate) strongDelegate = _webViewDelegate; if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:didFailProvisionalNavigation:withError:)]) { [strongDelegate webView:webView didFailProvisionalNavigation:navigation withError:error]; } } - (NSString*) _evaluateJavascript:(NSString*)javascriptCommand { [_webView evaluateJavaScript:javascriptCommand completionHandler:nil]; return NULL; } @end #endif ```
/content/code_sandbox/Pods/WebViewJavascriptBridge/WebViewJavascriptBridge/WKWebViewJavascriptBridge.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,483
```objective-c // // SDCycleScrollView.m // SDCycleScrollView // // Created by aier on 15-3-22. // /* ********************************************************************************* * * SDCycleScrollViewQQ185534916 * * bugbug * * :GSD_iOS * Email : gsdios@126.com * GitHub: path_to_url * * SDAutoLayout * CellTableviewLabelScrollView * AutoLayout * path_to_url * path_to_url * GitHubpath_to_url ********************************************************************************* */ #import "SDCycleScrollView.h" #import "SDCollectionViewCell.h" #import "UIView+SDExtension.h" #import "TAPageControl.h" #import "SDWebImageManager.h" #import "UIImageView+WebCache.h" #define kCycleScrollViewInitialPageControlDotSize CGSizeMake(10, 10) NSString * const ID = @"SDCycleScrollViewCell"; @interface SDCycleScrollView () <UICollectionViewDataSource, UICollectionViewDelegate> @property (nonatomic, weak) UICollectionView *mainView; // collectionView @property (nonatomic, weak) UICollectionViewFlowLayout *flowLayout; @property (nonatomic, strong) NSArray *imagePathsGroup; @property (nonatomic, weak) NSTimer *timer; @property (nonatomic, assign) NSInteger totalItemsCount; @property (nonatomic, weak) UIControl *pageControl; @property (nonatomic, strong) UIImageView *backgroundImageView; // imageURLs @end @implementation SDCycleScrollView - (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { [self initialization]; [self setupMainView]; } return self; } - (void)awakeFromNib { [super awakeFromNib]; [self initialization]; [self setupMainView]; } - (void)initialization { _pageControlAliment = SDCycleScrollViewPageContolAlimentCenter; _autoScrollTimeInterval = 2.0; _titleLabelTextColor = [UIColor whiteColor]; _titleLabelTextFont= [UIFont systemFontOfSize:14]; _titleLabelBackgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]; _titleLabelHeight = 30; _titleLabelTextAlignment = NSTextAlignmentLeft; _autoScroll = YES; _infiniteLoop = YES; _showPageControl = YES; _pageControlDotSize = kCycleScrollViewInitialPageControlDotSize; _pageControlBottomOffset = 0; _pageControlRightOffset = 0; _pageControlStyle = SDCycleScrollViewPageContolStyleClassic; _hidesForSinglePage = YES; _currentPageDotColor = [UIColor whiteColor]; _pageDotColor = [UIColor lightGrayColor]; _bannerImageViewContentMode = UIViewContentModeScaleToFill; self.backgroundColor = [UIColor lightGrayColor]; } + (instancetype)cycleScrollViewWithFrame:(CGRect)frame imageNamesGroup:(NSArray *)imageNamesGroup { SDCycleScrollView *cycleScrollView = [[self alloc] initWithFrame:frame]; cycleScrollView.localizationImageNamesGroup = [NSMutableArray arrayWithArray:imageNamesGroup]; return cycleScrollView; } + (instancetype)cycleScrollViewWithFrame:(CGRect)frame shouldInfiniteLoop:(BOOL)infiniteLoop imageNamesGroup:(NSArray *)imageNamesGroup { SDCycleScrollView *cycleScrollView = [[self alloc] initWithFrame:frame]; cycleScrollView.infiniteLoop = infiniteLoop; cycleScrollView.localizationImageNamesGroup = [NSMutableArray arrayWithArray:imageNamesGroup]; return cycleScrollView; } + (instancetype)cycleScrollViewWithFrame:(CGRect)frame imageURLStringsGroup:(NSArray *)imageURLsGroup { SDCycleScrollView *cycleScrollView = [[self alloc] initWithFrame:frame]; cycleScrollView.imageURLStringsGroup = [NSMutableArray arrayWithArray:imageURLsGroup]; return cycleScrollView; } + (instancetype)cycleScrollViewWithFrame:(CGRect)frame delegate:(id<SDCycleScrollViewDelegate>)delegate placeholderImage:(UIImage *)placeholderImage { SDCycleScrollView *cycleScrollView = [[self alloc] initWithFrame:frame]; cycleScrollView.delegate = delegate; cycleScrollView.placeholderImage = placeholderImage; return cycleScrollView; } // collectionView - (void)setupMainView { UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init]; flowLayout.minimumLineSpacing = 0; flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal; _flowLayout = flowLayout; UICollectionView *mainView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flowLayout]; mainView.backgroundColor = [UIColor clearColor]; mainView.pagingEnabled = YES; mainView.showsHorizontalScrollIndicator = NO; mainView.showsVerticalScrollIndicator = NO; [mainView registerClass:[SDCollectionViewCell class] forCellWithReuseIdentifier:ID]; mainView.dataSource = self; mainView.delegate = self; mainView.scrollsToTop = NO; [self addSubview:mainView]; _mainView = mainView; } #pragma mark - properties - (void)setDelegate:(id<SDCycleScrollViewDelegate>)delegate { _delegate = delegate; if ([self.delegate respondsToSelector:@selector(customCollectionViewCellClassForCycleScrollView:)] && [self.delegate customCollectionViewCellClassForCycleScrollView:self]) { [self.mainView registerClass:[self.delegate customCollectionViewCellClassForCycleScrollView:self] forCellWithReuseIdentifier:ID]; }else if ([self.delegate respondsToSelector:@selector(customCollectionViewCellNibForCycleScrollView:)] && [self.delegate customCollectionViewCellNibForCycleScrollView:self]) { [self.mainView registerNib:[self.delegate customCollectionViewCellNibForCycleScrollView:self] forCellWithReuseIdentifier:ID]; } } - (void)setPlaceholderImage:(UIImage *)placeholderImage { _placeholderImage = placeholderImage; if (!self.backgroundImageView) { UIImageView *bgImageView = [UIImageView new]; bgImageView.contentMode = UIViewContentModeScaleAspectFit; [self insertSubview:bgImageView belowSubview:self.mainView]; self.backgroundImageView = bgImageView; } self.backgroundImageView.image = placeholderImage; } - (void)setPageControlDotSize:(CGSize)pageControlDotSize { _pageControlDotSize = pageControlDotSize; [self setupPageControl]; if ([self.pageControl isKindOfClass:[TAPageControl class]]) { TAPageControl *pageContol = (TAPageControl *)_pageControl; pageContol.dotSize = pageControlDotSize; } } - (void)setShowPageControl:(BOOL)showPageControl { _showPageControl = showPageControl; _pageControl.hidden = !showPageControl; } - (void)setCurrentPageDotColor:(UIColor *)currentPageDotColor { _currentPageDotColor = currentPageDotColor; if ([self.pageControl isKindOfClass:[TAPageControl class]]) { TAPageControl *pageControl = (TAPageControl *)_pageControl; pageControl.dotColor = currentPageDotColor; } else { UIPageControl *pageControl = (UIPageControl *)_pageControl; pageControl.currentPageIndicatorTintColor = currentPageDotColor; } } - (void)setPageDotColor:(UIColor *)pageDotColor { _pageDotColor = pageDotColor; if ([self.pageControl isKindOfClass:[UIPageControl class]]) { UIPageControl *pageControl = (UIPageControl *)_pageControl; pageControl.pageIndicatorTintColor = pageDotColor; } } - (void)setCurrentPageDotImage:(UIImage *)currentPageDotImage { _currentPageDotImage = currentPageDotImage; if (self.pageControlStyle != SDCycleScrollViewPageContolStyleAnimated) { self.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated; } [self setCustomPageControlDotImage:currentPageDotImage isCurrentPageDot:YES]; } - (void)setPageDotImage:(UIImage *)pageDotImage { _pageDotImage = pageDotImage; if (self.pageControlStyle != SDCycleScrollViewPageContolStyleAnimated) { self.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated; } [self setCustomPageControlDotImage:pageDotImage isCurrentPageDot:NO]; } - (void)setCustomPageControlDotImage:(UIImage *)image isCurrentPageDot:(BOOL)isCurrentPageDot { if (!image || !self.pageControl) return; if ([self.pageControl isKindOfClass:[TAPageControl class]]) { TAPageControl *pageControl = (TAPageControl *)_pageControl; if (isCurrentPageDot) { pageControl.currentDotImage = image; } else { pageControl.dotImage = image; } } } - (void)setInfiniteLoop:(BOOL)infiniteLoop { _infiniteLoop = infiniteLoop; if (self.imagePathsGroup.count) { self.imagePathsGroup = self.imagePathsGroup; } } -(void)setAutoScroll:(BOOL)autoScroll{ _autoScroll = autoScroll; [self invalidateTimer]; if (_autoScroll) { [self setupTimer]; } } - (void)setScrollDirection:(UICollectionViewScrollDirection)scrollDirection { _scrollDirection = scrollDirection; _flowLayout.scrollDirection = scrollDirection; } - (void)setAutoScrollTimeInterval:(CGFloat)autoScrollTimeInterval { _autoScrollTimeInterval = autoScrollTimeInterval; [self setAutoScroll:self.autoScroll]; } - (void)setPageControlStyle:(SDCycleScrollViewPageContolStyle)pageControlStyle { _pageControlStyle = pageControlStyle; [self setupPageControl]; } - (void)setImagePathsGroup:(NSArray *)imagePathsGroup { [self invalidateTimer]; _imagePathsGroup = imagePathsGroup; _totalItemsCount = self.infiniteLoop ? self.imagePathsGroup.count * 100 : self.imagePathsGroup.count; if (imagePathsGroup.count > 1) { // !=1 count == 0 self.mainView.scrollEnabled = YES; [self setAutoScroll:self.autoScroll]; } else { self.mainView.scrollEnabled = NO; [self invalidateTimer]; } [self setupPageControl]; [self.mainView reloadData]; } - (void)setImageURLStringsGroup:(NSArray *)imageURLStringsGroup { _imageURLStringsGroup = imageURLStringsGroup; NSMutableArray *temp = [NSMutableArray new]; [_imageURLStringsGroup enumerateObjectsUsingBlock:^(NSString * obj, NSUInteger idx, BOOL * stop) { NSString *urlString; if ([obj isKindOfClass:[NSString class]]) { urlString = obj; } else if ([obj isKindOfClass:[NSURL class]]) { NSURL *url = (NSURL *)obj; urlString = [url absoluteString]; } if (urlString) { [temp addObject:urlString]; } }]; self.imagePathsGroup = [temp copy]; } - (void)setLocalizationImageNamesGroup:(NSArray *)localizationImageNamesGroup { _localizationImageNamesGroup = localizationImageNamesGroup; self.imagePathsGroup = [localizationImageNamesGroup copy]; } - (void)setTitlesGroup:(NSArray *)titlesGroup { _titlesGroup = titlesGroup; if (self.onlyDisplayText) { NSMutableArray *temp = [NSMutableArray new]; for (int i = 0; i < _titlesGroup.count; i++) { [temp addObject:@""]; } self.backgroundColor = [UIColor clearColor]; self.imageURLStringsGroup = [temp copy]; } } - (void)disableScrollGesture { self.mainView.canCancelContentTouches = NO; for (UIGestureRecognizer *gesture in self.mainView.gestureRecognizers) { if ([gesture isKindOfClass:[UIPanGestureRecognizer class]]) { [self.mainView removeGestureRecognizer:gesture]; } } } #pragma mark - actions - (void)setupTimer { [self invalidateTimer]; // NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:self.autoScrollTimeInterval target:self selector:@selector(automaticScroll) userInfo:nil repeats:YES]; _timer = timer; [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; } - (void)invalidateTimer { [_timer invalidate]; _timer = nil; } - (void)setupPageControl { if (_pageControl) [_pageControl removeFromSuperview]; // if (self.imagePathsGroup.count == 0 || self.onlyDisplayText) return; if ((self.imagePathsGroup.count == 1) && self.hidesForSinglePage) return; int indexOnPageControl = [self pageControlIndexWithCurrentCellIndex:[self currentIndex]]; switch (self.pageControlStyle) { case SDCycleScrollViewPageContolStyleAnimated: { TAPageControl *pageControl = [[TAPageControl alloc] init]; pageControl.numberOfPages = self.imagePathsGroup.count; pageControl.dotColor = self.currentPageDotColor; pageControl.userInteractionEnabled = NO; pageControl.currentPage = indexOnPageControl; [self addSubview:pageControl]; _pageControl = pageControl; } break; case SDCycleScrollViewPageContolStyleClassic: { UIPageControl *pageControl = [[UIPageControl alloc] init]; pageControl.numberOfPages = self.imagePathsGroup.count; pageControl.currentPageIndicatorTintColor = self.currentPageDotColor; pageControl.pageIndicatorTintColor = self.pageDotColor; pageControl.userInteractionEnabled = NO; pageControl.currentPage = indexOnPageControl; [self addSubview:pageControl]; _pageControl = pageControl; } break; default: break; } // pagecontroldot if (self.currentPageDotImage) { self.currentPageDotImage = self.currentPageDotImage; } if (self.pageDotImage) { self.pageDotImage = self.pageDotImage; } } - (void)automaticScroll { if (0 == _totalItemsCount) return; int currentIndex = [self currentIndex]; int targetIndex = currentIndex + 1; [self scrollToIndex:targetIndex]; } - (void)scrollToIndex:(int)targetIndex { if (targetIndex >= _totalItemsCount) { if (self.infiniteLoop) { targetIndex = _totalItemsCount * 0.5; [_mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO]; } return; } [_mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES]; } - (int)currentIndex { if (_mainView.sd_width == 0 || _mainView.sd_height == 0) { return 0; } int index = 0; if (_flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal) { index = (_mainView.contentOffset.x + _flowLayout.itemSize.width * 0.5) / _flowLayout.itemSize.width; } else { index = (_mainView.contentOffset.y + _flowLayout.itemSize.height * 0.5) / _flowLayout.itemSize.height; } return MAX(0, index); } - (int)pageControlIndexWithCurrentCellIndex:(NSInteger)index { return (int)index % self.imagePathsGroup.count; } - (void)clearCache { [[self class] clearImagesCache]; } + (void)clearImagesCache { [[[SDWebImageManager sharedManager] imageCache] clearDiskOnCompletion:nil]; } #pragma mark - life circles - (void)layoutSubviews { self.delegate = self.delegate; [super layoutSubviews]; _flowLayout.itemSize = self.frame.size; _mainView.frame = self.bounds; if (_mainView.contentOffset.x == 0 && _totalItemsCount) { int targetIndex = 0; if (self.infiniteLoop) { targetIndex = _totalItemsCount * 0.5; }else{ targetIndex = 0; } [_mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO]; } CGSize size = CGSizeZero; if ([self.pageControl isKindOfClass:[TAPageControl class]]) { TAPageControl *pageControl = (TAPageControl *)_pageControl; if (!(self.pageDotImage && self.currentPageDotImage && CGSizeEqualToSize(kCycleScrollViewInitialPageControlDotSize, self.pageControlDotSize))) { pageControl.dotSize = self.pageControlDotSize; } size = [pageControl sizeForNumberOfPages:self.imagePathsGroup.count]; } else { size = CGSizeMake(self.imagePathsGroup.count * self.pageControlDotSize.width * 1.5, self.pageControlDotSize.height); } CGFloat x = (self.sd_width - size.width) * 0.5; if (self.pageControlAliment == SDCycleScrollViewPageContolAlimentRight) { x = self.mainView.sd_width - size.width - 10; } CGFloat y = self.mainView.sd_height - size.height - 10; if ([self.pageControl isKindOfClass:[TAPageControl class]]) { TAPageControl *pageControl = (TAPageControl *)_pageControl; [pageControl sizeToFit]; } CGRect pageControlFrame = CGRectMake(x, y, size.width, size.height); pageControlFrame.origin.y -= self.pageControlBottomOffset; pageControlFrame.origin.x -= self.pageControlRightOffset; self.pageControl.frame = pageControlFrame; self.pageControl.hidden = !_showPageControl; if (self.backgroundImageView) { self.backgroundImageView.frame = self.bounds; } } //ViewTimer - (void)willMoveToSuperview:(UIView *)newSuperview { if (!newSuperview) { [self invalidateTimer]; } } //timer scrollViewDidScroll - (void)dealloc { _mainView.delegate = nil; _mainView.dataSource = nil; } #pragma mark - public actions - (void)adjustWhenControllerViewWillAppera { long targetIndex = [self currentIndex]; if (targetIndex < _totalItemsCount) { [_mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO]; } } #pragma mark - UICollectionViewDataSource - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return _totalItemsCount; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { SDCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath]; long itemIndex = [self pageControlIndexWithCurrentCellIndex:indexPath.item]; if ([self.delegate respondsToSelector:@selector(setupCustomCell:forIndex:cycleScrollView:)] && [self.delegate respondsToSelector:@selector(customCollectionViewCellClassForCycleScrollView:)] && [self.delegate customCollectionViewCellClassForCycleScrollView:self]) { [self.delegate setupCustomCell:cell forIndex:itemIndex cycleScrollView:self]; return cell; }else if ([self.delegate respondsToSelector:@selector(setupCustomCell:forIndex:cycleScrollView:)] && [self.delegate respondsToSelector:@selector(customCollectionViewCellNibForCycleScrollView:)] && [self.delegate customCollectionViewCellNibForCycleScrollView:self]) { [self.delegate setupCustomCell:cell forIndex:itemIndex cycleScrollView:self]; return cell; } NSString *imagePath = self.imagePathsGroup[itemIndex]; if (!self.onlyDisplayText && [imagePath isKindOfClass:[NSString class]]) { if ([imagePath hasPrefix:@"http"]) { [cell.imageView sd_setImageWithURL:[NSURL URLWithString:imagePath] placeholderImage:self.placeholderImage]; } else { UIImage *image = [UIImage imageNamed:imagePath]; if (!image) { image = [UIImage imageWithContentsOfFile:imagePath]; } cell.imageView.image = image; } } else if (!self.onlyDisplayText && [imagePath isKindOfClass:[UIImage class]]) { cell.imageView.image = (UIImage *)imagePath; } if (_titlesGroup.count && itemIndex < _titlesGroup.count) { cell.title = _titlesGroup[itemIndex]; } if (!cell.hasConfigured) { cell.titleLabelBackgroundColor = self.titleLabelBackgroundColor; cell.titleLabelHeight = self.titleLabelHeight; cell.titleLabelTextAlignment = self.titleLabelTextAlignment; cell.titleLabelTextColor = self.titleLabelTextColor; cell.titleLabelTextFont = self.titleLabelTextFont; cell.hasConfigured = YES; cell.imageView.contentMode = self.bannerImageViewContentMode; cell.clipsToBounds = YES; cell.onlyDisplayText = self.onlyDisplayText; } return cell; } - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { if ([self.delegate respondsToSelector:@selector(cycleScrollView:didSelectItemAtIndex:)]) { [self.delegate cycleScrollView:self didSelectItemAtIndex:[self pageControlIndexWithCurrentCellIndex:indexPath.item]]; } if (self.clickItemOperationBlock) { self.clickItemOperationBlock([self pageControlIndexWithCurrentCellIndex:indexPath.item]); } } #pragma mark - UIScrollViewDelegate - (void)scrollViewDidScroll:(UIScrollView *)scrollView { if (!self.imagePathsGroup.count) return; // timer int itemIndex = [self currentIndex]; int indexOnPageControl = [self pageControlIndexWithCurrentCellIndex:itemIndex]; if ([self.pageControl isKindOfClass:[TAPageControl class]]) { TAPageControl *pageControl = (TAPageControl *)_pageControl; pageControl.currentPage = indexOnPageControl; } else { UIPageControl *pageControl = (UIPageControl *)_pageControl; pageControl.currentPage = indexOnPageControl; } } - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { if (self.autoScroll) { [self invalidateTimer]; } } - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate { if (self.autoScroll) { [self setupTimer]; } } - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { [self scrollViewDidEndScrollingAnimation:self.mainView]; } - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView { if (!self.imagePathsGroup.count) return; // timer int itemIndex = [self currentIndex]; int indexOnPageControl = [self pageControlIndexWithCurrentCellIndex:itemIndex]; if ([self.delegate respondsToSelector:@selector(cycleScrollView:didScrollToIndex:)]) { [self.delegate cycleScrollView:self didScrollToIndex:indexOnPageControl]; } else if (self.itemDidScrollOperationBlock) { self.itemDidScrollOperationBlock(indexOnPageControl); } } - (void)makeScrollViewScrollToIndex:(NSInteger)index{ if (self.autoScroll) { [self invalidateTimer]; } if (0 == _totalItemsCount) return; [self scrollToIndex:(int)(_totalItemsCount * 0.5 + index)]; if (self.autoScroll) { [self setupTimer]; } } @end ```
/content/code_sandbox/Pods/SDCycleScrollView/SDCycleScrollView/Lib/SDCycleScrollView/SDCycleScrollView.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
5,019
```objective-c // // SDCollectionViewCell.h // SDCycleScrollView // // Created by aier on 15-3-22. // /* ********************************************************************************* * * SDCycleScrollViewQQ185534916 * * bugbug * * :GSD_iOS * Email : gsdios@126.com * GitHub: path_to_url * * SDAutoLayout * CellTableviewLabelScrollView * AutoLayout * path_to_url * path_to_url * GitHubpath_to_url ********************************************************************************* */ #import <UIKit/UIKit.h> @interface SDCollectionViewCell : UICollectionViewCell @property (weak, nonatomic) UIImageView *imageView; @property (copy, nonatomic) NSString *title; @property (nonatomic, strong) UIColor *titleLabelTextColor; @property (nonatomic, strong) UIFont *titleLabelTextFont; @property (nonatomic, strong) UIColor *titleLabelBackgroundColor; @property (nonatomic, assign) CGFloat titleLabelHeight; @property (nonatomic, assign) NSTextAlignment titleLabelTextAlignment; @property (nonatomic, assign) BOOL hasConfigured; /** */ @property (nonatomic, assign) BOOL onlyDisplayText; @end ```
/content/code_sandbox/Pods/SDCycleScrollView/SDCycleScrollView/Lib/SDCycleScrollView/SDCollectionViewCell.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
238
```objective-c // // SDCycleScrollView.h // SDCycleScrollView // // Created by aier on 15-3-22. // /* ********************************************************************************* * * SDCycleScrollViewQQ185534916 * * bugbug * * :GSD_iOS * Email : gsdios@126.com * GitHub: path_to_url * * SDAutoLayout * CellTableviewLabelScrollView * AutoLayout * path_to_url * path_to_url * GitHubpath_to_url ********************************************************************************* */ /* * 1.62 * 2016.04.21 */ #import <UIKit/UIKit.h> typedef enum { SDCycleScrollViewPageContolAlimentRight, SDCycleScrollViewPageContolAlimentCenter } SDCycleScrollViewPageContolAliment; typedef enum { SDCycleScrollViewPageContolStyleClassic, // SDCycleScrollViewPageContolStyleAnimated, // pagecontrol SDCycleScrollViewPageContolStyleNone // pagecontrol } SDCycleScrollViewPageContolStyle; @class SDCycleScrollView; @protocol SDCycleScrollViewDelegate <NSObject> @optional /** */ - (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index; /** */ - (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index; // cell // ========== cell ========== /** cellcellclass */ - (Class)customCollectionViewCellClassForCycleScrollView:(SDCycleScrollView *)view; /** cellcellNib */ - (UINib *)customCollectionViewCellNibForCycleScrollView:(SDCycleScrollView *)view; /** cellcell */ - (void)setupCustomCell:(UICollectionViewCell *)cell forIndex:(NSInteger)index cycleScrollView:(SDCycleScrollView *)view; @end @interface SDCycleScrollView : UIView /** */ + (instancetype)cycleScrollViewWithFrame:(CGRect)frame delegate:(id<SDCycleScrollViewDelegate>)delegate placeholderImage:(UIImage *)placeholderImage; + (instancetype)cycleScrollViewWithFrame:(CGRect)frame imageURLStringsGroup:(NSArray *)imageURLStringsGroup; /** */ + (instancetype)cycleScrollViewWithFrame:(CGRect)frame imageNamesGroup:(NSArray *)imageNamesGroup; /** 2,infiniteLoop: */ + (instancetype)cycleScrollViewWithFrame:(CGRect)frame shouldInfiniteLoop:(BOOL)infiniteLoop imageNamesGroup:(NSArray *)imageNamesGroup; ////////////////////// API ////////////////////// /** url string */ @property (nonatomic, strong) NSArray *imageURLStringsGroup; /** */ @property (nonatomic, strong) NSArray *titlesGroup; /** */ @property (nonatomic, strong) NSArray *localizationImageNamesGroup; ////////////////////// API ////////////////////// /** ,2s */ @property (nonatomic, assign) CGFloat autoScrollTimeInterval; /** ,Yes */ @property (nonatomic,assign) BOOL infiniteLoop; /** ,Yes */ @property (nonatomic,assign) BOOL autoScroll; /** */ @property (nonatomic, assign) UICollectionViewScrollDirection scrollDirection; @property (nonatomic, weak) id<SDCycleScrollViewDelegate> delegate; /** block */ @property (nonatomic, copy) void (^clickItemOperationBlock)(NSInteger currentIndex); /** block */ @property (nonatomic, copy) void (^itemDidScrollOperationBlock)(NSInteger currentIndex); /** index */ - (void)makeScrollViewScrollToIndex:(NSInteger)index; /** viewWillAppearviewWillAppear */ - (void)adjustWhenControllerViewWillAppera; ////////////////////// API ////////////////////// /** ContentMode UIViewContentModeScaleToFill */ @property (nonatomic, assign) UIViewContentMode bannerImageViewContentMode; /** */ @property (nonatomic, strong) UIImage *placeholderImage; /** */ @property (nonatomic, assign) BOOL showPageControl; /** pagecontrolYES */ @property(nonatomic) BOOL hidesForSinglePage; /** */ @property (nonatomic, assign) BOOL onlyDisplayText; /** pagecontrol */ @property (nonatomic, assign) SDCycleScrollViewPageContolStyle pageControlStyle; /** */ @property (nonatomic, assign) SDCycleScrollViewPageContolAliment pageControlAliment; /** */ @property (nonatomic, assign) CGFloat pageControlBottomOffset; /** */ @property (nonatomic, assign) CGFloat pageControlRightOffset; /** */ @property (nonatomic, assign) CGSize pageControlDotSize; /** */ @property (nonatomic, strong) UIColor *currentPageDotColor; /** */ @property (nonatomic, strong) UIColor *pageDotColor; /** */ @property (nonatomic, strong) UIImage *currentPageDotImage; /** */ @property (nonatomic, strong) UIImage *pageDotImage; /** label */ @property (nonatomic, strong) UIColor *titleLabelTextColor; /** label */ @property (nonatomic, strong) UIFont *titleLabelTextFont; /** label */ @property (nonatomic, strong) UIColor *titleLabelBackgroundColor; /** label */ @property (nonatomic, assign) CGFloat titleLabelHeight; /** label */ @property (nonatomic, assign) NSTextAlignment titleLabelTextAlignment; /** */ - (void)disableScrollGesture; ////////////////////// API ////////////////////// /** SDWebImage */ + (void)clearImagesCache; /** */ - (void)clearCache; @end ```
/content/code_sandbox/Pods/SDCycleScrollView/SDCycleScrollView/Lib/SDCycleScrollView/SDCycleScrollView.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,086
```objective-c // // UIView+SDExtension.m // SDRefreshView // // Created by aier on 15-2-23. // /* ********************************************************************************* * * SDCycleScrollViewQQ185534916 * * bugbug * * :GSD_iOS * Email : gsdios@126.com * GitHub: path_to_url * * SDAutoLayout * CellTableviewLabelScrollView * AutoLayout * path_to_url * path_to_url * GitHubpath_to_url ********************************************************************************* */ /* ********************************************************************************* * * bugbug * * :GSD_iOS * Email : gsdios@126.com * GitHub: path_to_url * * SDAutoLayout * CellTableviewLabelScrollView * AutoLayout * path_to_url * path_to_url * GitHubpath_to_url ********************************************************************************* */ #import "UIView+SDExtension.h" @implementation UIView (SDExtension) - (CGFloat)sd_height { return self.frame.size.height; } - (void)setSd_height:(CGFloat)sd_height { CGRect temp = self.frame; temp.size.height = sd_height; self.frame = temp; } - (CGFloat)sd_width { return self.frame.size.width; } - (void)setSd_width:(CGFloat)sd_width { CGRect temp = self.frame; temp.size.width = sd_width; self.frame = temp; } - (CGFloat)sd_y { return self.frame.origin.y; } - (void)setSd_y:(CGFloat)sd_y { CGRect temp = self.frame; temp.origin.y = sd_y; self.frame = temp; } - (CGFloat)sd_x { return self.frame.origin.x; } - (void)setSd_x:(CGFloat)sd_x { CGRect temp = self.frame; temp.origin.x = sd_x; self.frame = temp; } @end ```
/content/code_sandbox/Pods/SDCycleScrollView/SDCycleScrollView/Lib/SDCycleScrollView/UIView+SDExtension.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
418
```objective-c // // UIView+SDExtension.h // SDRefreshView // // Created by aier on 15-2-23. // /* ********************************************************************************* * * SDCycleScrollViewQQ185534916 * * bugbug * * :GSD_iOS * Email : gsdios@126.com * GitHub: path_to_url * * SDAutoLayout * CellTableviewLabelScrollView * AutoLayout * path_to_url * path_to_url * GitHubpath_to_url ********************************************************************************* */ #import <UIKit/UIKit.h> #define SDColorCreater(r, g, b, a) [UIColor colorWithRed:(r / 255.0) green:(g / 255.0) blue:(b / 255.0) alpha:a] @interface UIView (SDExtension) @property (nonatomic, assign) CGFloat sd_height; @property (nonatomic, assign) CGFloat sd_width; @property (nonatomic, assign) CGFloat sd_y; @property (nonatomic, assign) CGFloat sd_x; @end ```
/content/code_sandbox/Pods/SDCycleScrollView/SDCycleScrollView/Lib/SDCycleScrollView/UIView+SDExtension.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
218
```objective-c // // SDCollectionViewCell.m // SDCycleScrollView // // Created by aier on 15-3-22. // /* ********************************************************************************* * * SDCycleScrollViewQQ185534916 * * bugbug * * :GSD_iOS * Email : gsdios@126.com * GitHub: path_to_url * * SDAutoLayout * CellTableviewLabelScrollView * AutoLayout * path_to_url * path_to_url * GitHubpath_to_url ********************************************************************************* */ #import "SDCollectionViewCell.h" #import "UIView+SDExtension.h" @implementation SDCollectionViewCell { __weak UILabel *_titleLabel; } - (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { [self setupImageView]; [self setupTitleLabel]; } return self; } - (void)setTitleLabelBackgroundColor:(UIColor *)titleLabelBackgroundColor { _titleLabelBackgroundColor = titleLabelBackgroundColor; _titleLabel.backgroundColor = titleLabelBackgroundColor; } - (void)setTitleLabelTextColor:(UIColor *)titleLabelTextColor { _titleLabelTextColor = titleLabelTextColor; _titleLabel.textColor = titleLabelTextColor; } - (void)setTitleLabelTextFont:(UIFont *)titleLabelTextFont { _titleLabelTextFont = titleLabelTextFont; _titleLabel.font = titleLabelTextFont; } - (void)setupImageView { UIImageView *imageView = [[UIImageView alloc] init]; _imageView = imageView; [self.contentView addSubview:imageView]; } - (void)setupTitleLabel { UILabel *titleLabel = [[UILabel alloc] init]; _titleLabel = titleLabel; _titleLabel.hidden = YES; [self.contentView addSubview:titleLabel]; } - (void)setTitle:(NSString *)title { _title = [title copy]; _titleLabel.text = [NSString stringWithFormat:@" %@", title]; if (_titleLabel.hidden) { _titleLabel.hidden = NO; } } -(void)setTitleLabelTextAlignment:(NSTextAlignment)titleLabelTextAlignment { _titleLabelTextAlignment = titleLabelTextAlignment; _titleLabel.textAlignment = titleLabelTextAlignment; } - (void)layoutSubviews { [super layoutSubviews]; if (self.onlyDisplayText) { _titleLabel.frame = self.bounds; } else { _imageView.frame = self.bounds; CGFloat titleLabelW = self.sd_width; CGFloat titleLabelH = _titleLabelHeight; CGFloat titleLabelX = 0; CGFloat titleLabelY = self.sd_height - titleLabelH; _titleLabel.frame = CGRectMake(titleLabelX, titleLabelY, titleLabelW, titleLabelH); } } @end ```
/content/code_sandbox/Pods/SDCycleScrollView/SDCycleScrollView/Lib/SDCycleScrollView/SDCollectionViewCell.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
556
```objective-c // // TAPageControl.h // TAPageControl // // Created by Tanguy Aladenise on 2015-01-21. // #import <UIKit/UIKit.h> @protocol TAPageControlDelegate; @interface TAPageControl : UIControl /** * Dot view customization properties */ /** * The Class of your custom UIView, make sure to respect the TAAbstractDotView class. */ @property (nonatomic) Class dotViewClass; /** * UIImage to represent a dot. */ @property (nonatomic) UIImage *dotImage; /** * UIImage to represent current page dot. */ @property (nonatomic) UIImage *currentDotImage; /** * Dot size for dot views. Default is 8 by 8. */ @property (nonatomic) CGSize dotSize; @property (nonatomic, strong) UIColor *dotColor; /** * Spacing between two dot views. Default is 8. */ @property (nonatomic) NSInteger spacingBetweenDots; /** * Page control setup properties */ /** * Delegate for TAPageControl */ @property(nonatomic,assign) id<TAPageControlDelegate> delegate; /** * Number of pages for control. Default is 0. */ @property (nonatomic) NSInteger numberOfPages; /** * Current page on which control is active. Default is 0. */ @property (nonatomic) NSInteger currentPage; /** * Hide the control if there is only one page. Default is NO. */ @property (nonatomic) BOOL hidesForSinglePage; /** * Let the control know if should grow bigger by keeping center, or just get longer (right side expanding). By default YES. */ @property (nonatomic) BOOL shouldResizeFromCenter; /** * Return the minimum size required to display control properly for the given page count. * * @param pageCount Number of dots that will require display * * @return The CGSize being the minimum size required. */ - (CGSize)sizeForNumberOfPages:(NSInteger)pageCount; @end @protocol TAPageControlDelegate <NSObject> @optional - (void)TAPageControl:(TAPageControl *)pageControl didSelectPageAtIndex:(NSInteger)index; @end ```
/content/code_sandbox/Pods/SDCycleScrollView/SDCycleScrollView/Lib/SDCycleScrollView/PageControl/TAPageControl.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
444
```objective-c // // TADotView.m // TAPageControl // // Created by Tanguy Aladenise on 2015-01-22. // #import "TADotView.h" @implementation TADotView - (instancetype)init { self = [super init]; if (self) { [self initialization]; } return self; } - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self initialization]; } return self; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) { [self initialization]; } return self; } - (void)initialization { self.backgroundColor = [UIColor clearColor]; self.layer.cornerRadius = CGRectGetWidth(self.frame) / 2; self.layer.borderColor = [UIColor whiteColor].CGColor; self.layer.borderWidth = 2; } - (void)changeActivityState:(BOOL)active { if (active) { self.backgroundColor = [UIColor whiteColor]; } else { self.backgroundColor = [UIColor clearColor]; } } @end ```
/content/code_sandbox/Pods/SDCycleScrollView/SDCycleScrollView/Lib/SDCycleScrollView/PageControl/TADotView.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
258
```objective-c // // TAAbstractDotView.h // TAPageControl // // Created by Tanguy Aladenise on 2015-01-22. // #import <UIKit/UIKit.h> @interface TAAbstractDotView : UIView /** * A method call let view know which state appearance it should take. Active meaning it's current page. Inactive not the current page. * * @param active BOOL to tell if view is active or not */ - (void)changeActivityState:(BOOL)active; @end ```
/content/code_sandbox/Pods/SDCycleScrollView/SDCycleScrollView/Lib/SDCycleScrollView/PageControl/TAAbstractDotView.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
113
```objective-c // // TAAbstractDotView.m // TAPageControl // // Created by Tanguy Aladenise on 2015-01-22. // #import "TAAbstractDotView.h" @implementation TAAbstractDotView - (id)init { @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"You must override %@ in %@", NSStringFromSelector(_cmd), self.class] userInfo:nil]; } - (void)changeActivityState:(BOOL)active { @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"You must override %@ in %@", NSStringFromSelector(_cmd), self.class] userInfo:nil]; } @end ```
/content/code_sandbox/Pods/SDCycleScrollView/SDCycleScrollView/Lib/SDCycleScrollView/PageControl/TAAbstractDotView.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
155
```objective-c // // TAAnimatedDotView.m // TAPageControl // // Created by Tanguy Aladenise on 2015-01-22. // #import "TAAnimatedDotView.h" static CGFloat const kAnimateDuration = 1; @implementation TAAnimatedDotView - (instancetype)init { self = [super init]; if (self) { [self initialization]; } return self; } - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self initialization]; } return self; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) { [self initialization]; } return self; } - (void)setDotColor:(UIColor *)dotColor { _dotColor = dotColor; self.layer.borderColor = dotColor.CGColor; } - (void)initialization { _dotColor = [UIColor whiteColor]; self.backgroundColor = [UIColor clearColor]; self.layer.cornerRadius = CGRectGetWidth(self.frame) / 2; self.layer.borderColor = [UIColor whiteColor].CGColor; self.layer.borderWidth = 2; } - (void)changeActivityState:(BOOL)active { if (active) { [self animateToActiveState]; } else { [self animateToDeactiveState]; } } - (void)animateToActiveState { [UIView animateWithDuration:kAnimateDuration delay:0 usingSpringWithDamping:.5 initialSpringVelocity:-20 options:UIViewAnimationOptionCurveLinear animations:^{ self.backgroundColor = _dotColor; self.transform = CGAffineTransformMakeScale(1.4, 1.4); } completion:nil]; } - (void)animateToDeactiveState { [UIView animateWithDuration:kAnimateDuration delay:0 usingSpringWithDamping:.5 initialSpringVelocity:0 options:UIViewAnimationOptionCurveLinear animations:^{ self.backgroundColor = [UIColor clearColor]; self.transform = CGAffineTransformIdentity; } completion:nil]; } @end ```
/content/code_sandbox/Pods/SDCycleScrollView/SDCycleScrollView/Lib/SDCycleScrollView/PageControl/TAAnimatedDotView.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
446
```objective-c // // TAPageControl.m // TAPageControl // // Created by Tanguy Aladenise on 2015-01-21. // #import "TAPageControl.h" #import "TAAbstractDotView.h" #import "TAAnimatedDotView.h" #import "TADotView.h" /** * Default number of pages for initialization */ static NSInteger const kDefaultNumberOfPages = 0; /** * Default current page for initialization */ static NSInteger const kDefaultCurrentPage = 0; /** * Default setting for hide for single page feature. For initialization */ static BOOL const kDefaultHideForSinglePage = NO; /** * Default setting for shouldResizeFromCenter. For initialiation */ static BOOL const kDefaultShouldResizeFromCenter = YES; /** * Default spacing between dots */ static NSInteger const kDefaultSpacingBetweenDots = 8; /** * Default dot size */ static CGSize const kDefaultDotSize = {8, 8}; @interface TAPageControl() /** * Array of dot views for reusability and touch events. */ @property (strong, nonatomic) NSMutableArray *dots; @end @implementation TAPageControl #pragma mark - Lifecycle - (id)init { self = [super init]; if (self) { [self initialization]; } return self; } - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self initialization]; } return self; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) { [self initialization]; } return self; } /** * Default setup when initiating control */ - (void)initialization { self.dotViewClass = [TAAnimatedDotView class]; self.spacingBetweenDots = kDefaultSpacingBetweenDots; self.numberOfPages = kDefaultNumberOfPages; self.currentPage = kDefaultCurrentPage; self.hidesForSinglePage = kDefaultHideForSinglePage; self.shouldResizeFromCenter = kDefaultShouldResizeFromCenter; } #pragma mark - Touch event - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; if (touch.view != self) { NSInteger index = [self.dots indexOfObject:touch.view]; if ([self.delegate respondsToSelector:@selector(TAPageControl:didSelectPageAtIndex:)]) { [self.delegate TAPageControl:self didSelectPageAtIndex:index]; } } } #pragma mark - Layout /** * Resizes and moves the receiver view so it just encloses its subviews. */ - (void)sizeToFit { [self updateFrame:YES]; } - (CGSize)sizeForNumberOfPages:(NSInteger)pageCount { return CGSizeMake((self.dotSize.width + self.spacingBetweenDots) * pageCount - self.spacingBetweenDots , self.dotSize.height); } /** * Will update dots display and frame. Reuse existing views or instantiate one if required. Update their position in case frame changed. */ - (void)updateDots { if (self.numberOfPages == 0) { return; } for (NSInteger i = 0; i < self.numberOfPages; i++) { UIView *dot; if (i < self.dots.count) { dot = [self.dots objectAtIndex:i]; } else { dot = [self generateDotView]; } [self updateDotFrame:dot atIndex:i]; } [self changeActivity:YES atIndex:self.currentPage]; [self hideForSinglePage]; } /** * Update frame control to fit current number of pages. It will apply required size if authorize and required. * * @param overrideExistingFrame BOOL to allow frame to be overriden. Meaning the required size will be apply no mattter what. */ - (void)updateFrame:(BOOL)overrideExistingFrame { CGPoint center = self.center; CGSize requiredSize = [self sizeForNumberOfPages:self.numberOfPages]; // We apply requiredSize only if authorize to and necessary if (overrideExistingFrame || ((CGRectGetWidth(self.frame) < requiredSize.width || CGRectGetHeight(self.frame) < requiredSize.height) && !overrideExistingFrame)) { self.frame = CGRectMake(CGRectGetMinX(self.frame), CGRectGetMinY(self.frame), requiredSize.width, requiredSize.height); if (self.shouldResizeFromCenter) { self.center = center; } } [self resetDotViews]; } /** * Update the frame of a specific dot at a specific index * * @param dot Dot view * @param index Page index of dot */ - (void)updateDotFrame:(UIView *)dot atIndex:(NSInteger)index { // Dots are always centered within view CGFloat x = (self.dotSize.width + self.spacingBetweenDots) * index + ( (CGRectGetWidth(self.frame) - [self sizeForNumberOfPages:self.numberOfPages].width) / 2); CGFloat y = (CGRectGetHeight(self.frame) - self.dotSize.height) / 2; dot.frame = CGRectMake(x, y, self.dotSize.width, self.dotSize.height); } #pragma mark - Utils /** * Generate a dot view and add it to the collection * * @return The UIView object representing a dot */ - (UIView *)generateDotView { UIView *dotView; if (self.dotViewClass) { dotView = [[self.dotViewClass alloc] initWithFrame:CGRectMake(0, 0, self.dotSize.width, self.dotSize.height)]; if ([dotView isKindOfClass:[TAAnimatedDotView class]] && self.dotColor) { ((TAAnimatedDotView *)dotView).dotColor = self.dotColor; } } else { dotView = [[UIImageView alloc] initWithImage:self.dotImage]; dotView.frame = CGRectMake(0, 0, self.dotSize.width, self.dotSize.height); } if (dotView) { [self addSubview:dotView]; [self.dots addObject:dotView]; } dotView.userInteractionEnabled = YES; return dotView; } /** * Change activity state of a dot view. Current/not currrent. * * @param active Active state to apply * @param index Index of dot for state update */ - (void)changeActivity:(BOOL)active atIndex:(NSInteger)index { if (self.dotViewClass) { TAAbstractDotView *abstractDotView = (TAAbstractDotView *)[self.dots objectAtIndex:index]; if ([abstractDotView respondsToSelector:@selector(changeActivityState:)]) { [abstractDotView changeActivityState:active]; } else { NSLog(@"Custom view : %@ must implement an 'changeActivityState' method or you can subclass %@ to help you.", self.dotViewClass, [TAAbstractDotView class]); } } else if (self.dotImage && self.currentDotImage) { UIImageView *dotView = (UIImageView *)[self.dots objectAtIndex:index]; dotView.image = (active) ? self.currentDotImage : self.dotImage; } } - (void)resetDotViews { for (UIView *dotView in self.dots) { [dotView removeFromSuperview]; } [self.dots removeAllObjects]; [self updateDots]; } - (void)hideForSinglePage { if (self.dots.count == 1 && self.hidesForSinglePage) { self.hidden = YES; } else { self.hidden = NO; } } #pragma mark - Setters - (void)setNumberOfPages:(NSInteger)numberOfPages { _numberOfPages = numberOfPages; // Update dot position to fit new number of pages [self resetDotViews]; } - (void)setSpacingBetweenDots:(NSInteger)spacingBetweenDots { _spacingBetweenDots = spacingBetweenDots; [self resetDotViews]; } - (void)setCurrentPage:(NSInteger)currentPage { // If no pages, no current page to treat. if (self.numberOfPages == 0 || currentPage == _currentPage) { _currentPage = currentPage; return; } // Pre set [self changeActivity:NO atIndex:_currentPage]; _currentPage = currentPage; // Post set [self changeActivity:YES atIndex:_currentPage]; } - (void)setDotImage:(UIImage *)dotImage { _dotImage = dotImage; [self resetDotViews]; self.dotViewClass = nil; } - (void)setCurrentDotImage:(UIImage *)currentDotimage { _currentDotImage = currentDotimage; [self resetDotViews]; self.dotViewClass = nil; } - (void)setDotViewClass:(Class)dotViewClass { _dotViewClass = dotViewClass; self.dotSize = CGSizeZero; [self resetDotViews]; } #pragma mark - Getters - (NSMutableArray *)dots { if (!_dots) { _dots = [[NSMutableArray alloc] init]; } return _dots; } - (CGSize)dotSize { // Dot size logic depending on the source of the dot view if (self.dotImage && CGSizeEqualToSize(_dotSize, CGSizeZero)) { _dotSize = self.dotImage.size; } else if (self.dotViewClass && CGSizeEqualToSize(_dotSize, CGSizeZero)) { _dotSize = kDefaultDotSize; return _dotSize; } return _dotSize; } @end ```
/content/code_sandbox/Pods/SDCycleScrollView/SDCycleScrollView/Lib/SDCycleScrollView/PageControl/TAPageControl.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,082
```objective-c // // TADotView.h // TAPageControl // // Created by Tanguy Aladenise on 2015-01-22. // #import "TAAbstractDotView.h" @interface TADotView : TAAbstractDotView @end ```
/content/code_sandbox/Pods/SDCycleScrollView/SDCycleScrollView/Lib/SDCycleScrollView/PageControl/TADotView.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
59
```objective-c // // TAAnimatedDotView.h // TAPageControl // // Created by Tanguy Aladenise on 2015-01-22. // #import "TAAbstractDotView.h" @interface TAAnimatedDotView : TAAbstractDotView @property (nonatomic, strong) UIColor *dotColor; @end ```
/content/code_sandbox/Pods/SDCycleScrollView/SDCycleScrollView/Lib/SDCycleScrollView/PageControl/TAAnimatedDotView.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
70
```objective-c #import <Foundation/Foundation.h> @interface PodsDummy_SDWebImage : NSObject @end @implementation PodsDummy_SDWebImage @end ```
/content/code_sandbox/Pods/Target Support Files/SDWebImage/SDWebImage-dummy.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
25
```objective-c #import <Foundation/Foundation.h> @interface PodsDummy_WebViewJavascriptBridge : NSObject @end @implementation PodsDummy_WebViewJavascriptBridge @end ```
/content/code_sandbox/Pods/Target Support Files/WebViewJavascriptBridge/WebViewJavascriptBridge-dummy.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
27
```objective-c #import <Foundation/Foundation.h> @interface PodsDummy_SDCycleScrollView : NSObject @end @implementation PodsDummy_SDCycleScrollView @end ```
/content/code_sandbox/Pods/Target Support Files/SDCycleScrollView/SDCycleScrollView-dummy.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
27
```shell #!/bin/sh set -e mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt > "$RESOURCES_TO_COPY" XCASSET_FILES=() # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: path_to_url RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") case "${TARGETED_DEVICE_FAMILY}" in 1,2) TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" ;; 1) TARGET_DEVICE_ARGS="--target-device iphone" ;; 2) TARGET_DEVICE_ARGS="--target-device ipad" ;; 3) TARGET_DEVICE_ARGS="--target-device tv" ;; 4) TARGET_DEVICE_ARGS="--target-device watch" ;; *) TARGET_DEVICE_ARGS="--target-device mac" ;; esac install_resource() { if [[ "$1" = /* ]] ; then RESOURCE_PATH="$1" else RESOURCE_PATH="${PODS_ROOT}/$1" fi if [[ ! -e "$RESOURCE_PATH" ]] ; then cat << EOM error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. EOM exit 1 fi case $RESOURCE_PATH in *.storyboard) echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" || true ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.xib) echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" || true ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.framework) echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" ;; *.xcdatamodel) echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" || true xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" ;; *.xcdatamodeld) echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" || true xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" ;; *.xcmappingmodel) echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" || true xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" ;; *.xcassets) ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH" XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") ;; *) echo "$RESOURCE_PATH" || true echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" ;; esac } mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" fi rm -f "$RESOURCES_TO_COPY" if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ] then # Find all other xcassets (this unfortunately includes those of path pods and other targets). OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) while read line; do if [[ $line != "${PODS_ROOT}*" ]]; then XCASSET_FILES+=("$line") fi done <<<"$OTHER_XCASSETS" printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" fi ```
/content/code_sandbox/Pods/Target Support Files/Pods-BigShow1949/Pods-BigShow1949-resources.sh
shell
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,413
```objective-c #import <Foundation/Foundation.h> @interface PodsDummy_Pods_BigShow1949 : NSObject @end @implementation PodsDummy_Pods_BigShow1949 @end ```
/content/code_sandbox/Pods/Target Support Files/Pods-BigShow1949/Pods-BigShow1949-dummy.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
31
```shell #!/bin/sh set -e echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" # Used as a return value for each invocation of `strip_invalid_archs` function. STRIP_BINARY_RETVAL=0 # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: path_to_url RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") # Copies and strips a vendored framework install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # Use filter instead of exclude so missing patterns don't throw errors. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Copies and strips a vendored dSYM install_dsym() { local source="$1" if [ -r "$source" ]; then # Copy the dSYM into a the targets temp dir. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" local basename basename="$(basename -s .framework.dSYM "$source")" binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then strip_invalid_archs "$binary" fi if [[ $STRIP_BINARY_RETVAL == 1 ]]; then # Move the stripped file into its final destination. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" else # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" fi fi } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements '$1'" if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then code_sign_cmd="$code_sign_cmd &" fi echo "$code_sign_cmd" eval "$code_sign_cmd" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current target binary binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" # Intersect them with the architectures we are building for intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" # If there are no archs supported by this binary then warn the user if [[ -z "$intersected_archs" ]]; then echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." STRIP_BINARY_RETVAL=0 return fi stripped="" for arch in $binary_archs; do if ! [[ "${ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi STRIP_BINARY_RETVAL=1 } if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait fi ```
/content/code_sandbox/Pods/Target Support Files/Pods-BigShow1949/Pods-BigShow1949-frameworks.sh
shell
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,766
```markdown # Acknowledgements This application makes use of the following third party libraries: ## SDCycleScrollView Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## SDWebImage Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## WebViewJavascriptBridge Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## YYModel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Generated by CocoaPods - path_to_url ```
/content/code_sandbox/Pods/Target Support Files/Pods-BigShow1949/Pods-BigShow1949-acknowledgements.markdown
markdown
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
878
```objective-c #import <Foundation/Foundation.h> @interface PodsDummy_YYModel : NSObject @end @implementation PodsDummy_YYModel @end ```
/content/code_sandbox/Pods/Target Support Files/YYModel/YYModel-dummy.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
25
```objective-c // // YYClassInfo.h // YYModel <path_to_url // // Created by ibireme on 15/5/9. // // 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> #import <objc/runtime.h> NS_ASSUME_NONNULL_BEGIN /** Type encoding's type. */ typedef NS_OPTIONS(NSUInteger, YYEncodingType) { YYEncodingTypeMask = 0xFF, ///< mask of type value YYEncodingTypeUnknown = 0, ///< unknown YYEncodingTypeVoid = 1, ///< void YYEncodingTypeBool = 2, ///< bool YYEncodingTypeInt8 = 3, ///< char / BOOL YYEncodingTypeUInt8 = 4, ///< unsigned char YYEncodingTypeInt16 = 5, ///< short YYEncodingTypeUInt16 = 6, ///< unsigned short YYEncodingTypeInt32 = 7, ///< int YYEncodingTypeUInt32 = 8, ///< unsigned int YYEncodingTypeInt64 = 9, ///< long long YYEncodingTypeUInt64 = 10, ///< unsigned long long YYEncodingTypeFloat = 11, ///< float YYEncodingTypeDouble = 12, ///< double YYEncodingTypeLongDouble = 13, ///< long double YYEncodingTypeObject = 14, ///< id YYEncodingTypeClass = 15, ///< Class YYEncodingTypeSEL = 16, ///< SEL YYEncodingTypeBlock = 17, ///< block YYEncodingTypePointer = 18, ///< void* YYEncodingTypeStruct = 19, ///< struct YYEncodingTypeUnion = 20, ///< union YYEncodingTypeCString = 21, ///< char* YYEncodingTypeCArray = 22, ///< char[10] (for example) YYEncodingTypeQualifierMask = 0xFF00, ///< mask of qualifier YYEncodingTypeQualifierConst = 1 << 8, ///< const YYEncodingTypeQualifierIn = 1 << 9, ///< in YYEncodingTypeQualifierInout = 1 << 10, ///< inout YYEncodingTypeQualifierOut = 1 << 11, ///< out YYEncodingTypeQualifierBycopy = 1 << 12, ///< bycopy YYEncodingTypeQualifierByref = 1 << 13, ///< byref YYEncodingTypeQualifierOneway = 1 << 14, ///< oneway YYEncodingTypePropertyMask = 0xFF0000, ///< mask of property YYEncodingTypePropertyReadonly = 1 << 16, ///< readonly YYEncodingTypePropertyCopy = 1 << 17, ///< copy YYEncodingTypePropertyRetain = 1 << 18, ///< retain YYEncodingTypePropertyNonatomic = 1 << 19, ///< nonatomic YYEncodingTypePropertyWeak = 1 << 20, ///< weak YYEncodingTypePropertyCustomGetter = 1 << 21, ///< getter= YYEncodingTypePropertyCustomSetter = 1 << 22, ///< setter= YYEncodingTypePropertyDynamic = 1 << 23, ///< @dynamic }; /** Get the type from a Type-Encoding string. @discussion See also: path_to_url path_to_url @param typeEncoding A Type-Encoding string. @return The encoding type. */ YYEncodingType YYEncodingGetType(const char *typeEncoding); /** Instance variable information. */ @interface YYClassIvarInfo : NSObject @property (nonatomic, assign, readonly) Ivar ivar; ///< ivar opaque struct @property (nonatomic, strong, readonly) NSString *name; ///< Ivar's name @property (nonatomic, assign, readonly) ptrdiff_t offset; ///< Ivar's offset @property (nonatomic, strong, readonly) NSString *typeEncoding; ///< Ivar's type encoding @property (nonatomic, assign, readonly) YYEncodingType type; ///< Ivar's type /** Creates and returns an ivar info object. @param ivar ivar opaque struct @return A new object, or nil if an error occurs. */ - (instancetype)initWithIvar:(Ivar)ivar; @end /** Method information. */ @interface YYClassMethodInfo : NSObject @property (nonatomic, assign, readonly) Method method; ///< method opaque struct @property (nonatomic, strong, readonly) NSString *name; ///< method name @property (nonatomic, assign, readonly) SEL sel; ///< method's selector @property (nonatomic, assign, readonly) IMP imp; ///< method's implementation @property (nonatomic, strong, readonly) NSString *typeEncoding; ///< method's parameter and return types @property (nonatomic, strong, readonly) NSString *returnTypeEncoding; ///< return value's type @property (nullable, nonatomic, strong, readonly) NSArray<NSString *> *argumentTypeEncodings; ///< array of arguments' type /** Creates and returns a method info object. @param method method opaque struct @return A new object, or nil if an error occurs. */ - (instancetype)initWithMethod:(Method)method; @end /** Property information. */ @interface YYClassPropertyInfo : NSObject @property (nonatomic, assign, readonly) objc_property_t property; ///< property's opaque struct @property (nonatomic, strong, readonly) NSString *name; ///< property's name @property (nonatomic, assign, readonly) YYEncodingType type; ///< property's type @property (nonatomic, strong, readonly) NSString *typeEncoding; ///< property's encoding value @property (nonatomic, strong, readonly) NSString *ivarName; ///< property's ivar name @property (nullable, nonatomic, assign, readonly) Class cls; ///< may be nil @property (nullable, nonatomic, strong, readonly) NSArray<NSString *> *protocols; ///< may nil @property (nonatomic, assign, readonly) SEL getter; ///< getter (nonnull) @property (nonatomic, assign, readonly) SEL setter; ///< setter (nonnull) /** Creates and returns a property info object. @param property property opaque struct @return A new object, or nil if an error occurs. */ - (instancetype)initWithProperty:(objc_property_t)property; @end /** Class information for a class. */ @interface YYClassInfo : NSObject @property (nonatomic, assign, readonly) Class cls; ///< class object @property (nullable, nonatomic, assign, readonly) Class superCls; ///< super class object @property (nullable, nonatomic, assign, readonly) Class metaCls; ///< class's meta class object @property (nonatomic, readonly) BOOL isMeta; ///< whether this class is meta class @property (nonatomic, strong, readonly) NSString *name; ///< class name @property (nullable, nonatomic, strong, readonly) YYClassInfo *superClassInfo; ///< super class's class info @property (nullable, nonatomic, strong, readonly) NSDictionary<NSString *, YYClassIvarInfo *> *ivarInfos; ///< ivars @property (nullable, nonatomic, strong, readonly) NSDictionary<NSString *, YYClassMethodInfo *> *methodInfos; ///< methods @property (nullable, nonatomic, strong, readonly) NSDictionary<NSString *, YYClassPropertyInfo *> *propertyInfos; ///< properties /** If the class is changed (for example: you add a method to this class with 'class_addMethod()'), you should call this method to refresh the class info cache. After called this method, `needUpdate` will returns `YES`, and you should call 'classInfoWithClass' or 'classInfoWithClassName' to get the updated class info. */ - (void)setNeedUpdate; /** If this method returns `YES`, you should stop using this instance and call `classInfoWithClass` or `classInfoWithClassName` to get the updated class info. @return Whether this class info need update. */ - (BOOL)needUpdate; /** Get the class info of a specified Class. @discussion This method will cache the class info and super-class info at the first access to the Class. This method is thread-safe. @param cls A class. @return A class info, or nil if an error occurs. */ + (nullable instancetype)classInfoWithClass:(Class)cls; /** Get the class info of a specified Class. @discussion This method will cache the class info and super-class info at the first access to the Class. This method is thread-safe. @param className A class name. @return A class info, or nil if an error occurs. */ + (nullable instancetype)classInfoWithClassName:(NSString *)className; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/Pods/Headers/Public/YYModel/YYClassInfo.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,893
```objective-c // // YYModel.h // YYModel <path_to_url // // Created by ibireme on 15/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 <Foundation/Foundation.h> #if __has_include(<YYModel/YYModel.h>) FOUNDATION_EXPORT double YYModelVersionNumber; FOUNDATION_EXPORT const unsigned char YYModelVersionString[]; #import <YYModel/NSObject+YYModel.h> #import <YYModel/YYClassInfo.h> #else #import "NSObject+YYModel.h" #import "YYClassInfo.h" #endif ```
/content/code_sandbox/Pods/Headers/Public/YYModel/YYModel.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
140
```objective-c // // NSObject+YYModel.h // YYModel <path_to_url // // Created by ibireme on 15/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 <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** Provide some data-model method: * Convert json to any object, or convert any object to json. * Set object properties with a key-value dictionary (like KVC). * Implementations of `NSCoding`, `NSCopying`, `-hash` and `-isEqual:`. See `YYModel` protocol for custom methods. Sample Code: ********************** json convertor ********************* @interface YYAuthor : NSObject @property (nonatomic, strong) NSString *name; @property (nonatomic, assign) NSDate *birthday; @end @implementation YYAuthor @end @interface YYBook : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, assign) NSUInteger pages; @property (nonatomic, strong) YYAuthor *author; @end @implementation YYBook @end int main() { // create model from json YYBook *book = [YYBook yy_modelWithJSON:@"{\"name\": \"Harry Potter\", \"pages\": 256, \"author\": {\"name\": \"J.K.Rowling\", \"birthday\": \"1965-07-31\" }}"]; // convert model to json NSString *json = [book yy_modelToJSONString]; // {"author":{"name":"J.K.Rowling","birthday":"1965-07-31T00:00:00+0000"},"name":"Harry Potter","pages":256} } ********************** Coding/Copying/hash/equal ********************* @interface YYShadow :NSObject <NSCoding, NSCopying> @property (nonatomic, copy) NSString *name; @property (nonatomic, assign) CGSize size; @end @implementation YYShadow - (void)encodeWithCoder:(NSCoder *)aCoder { [self yy_modelEncodeWithCoder:aCoder]; } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; return [self yy_modelInitWithCoder:aDecoder]; } - (id)copyWithZone:(NSZone *)zone { return [self yy_modelCopy]; } - (NSUInteger)hash { return [self yy_modelHash]; } - (BOOL)isEqual:(id)object { return [self yy_modelIsEqual:object]; } @end */ @interface NSObject (YYModel) /** Creates and returns a new instance of the receiver from a json. This method is thread-safe. @param json A json object in `NSDictionary`, `NSString` or `NSData`. @return A new instance created from the json, or nil if an error occurs. */ + (nullable instancetype)yy_modelWithJSON:(id)json; /** Creates and returns a new instance of the receiver from a key-value dictionary. This method is thread-safe. @param dictionary A key-value dictionary mapped to the instance's properties. Any invalid key-value pair in dictionary will be ignored. @return A new instance created from the dictionary, or nil if an error occurs. @discussion The key in `dictionary` will mapped to the reciever's property name, and the value will set to the property. If the value's type does not match the property, this method will try to convert the value based on these rules: `NSString` or `NSNumber` -> c number, such as BOOL, int, long, float, NSUInteger... `NSString` -> NSDate, parsed with format "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd". `NSString` -> NSURL. `NSValue` -> struct or union, such as CGRect, CGSize, ... `NSString` -> SEL, Class. */ + (nullable instancetype)yy_modelWithDictionary:(NSDictionary *)dictionary; /** Set the receiver's properties with a json object. @discussion Any invalid data in json will be ignored. @param json A json object of `NSDictionary`, `NSString` or `NSData`, mapped to the receiver's properties. @return Whether succeed. */ - (BOOL)yy_modelSetWithJSON:(id)json; /** Set the receiver's properties with a key-value dictionary. @param dic A key-value dictionary mapped to the receiver's properties. Any invalid key-value pair in dictionary will be ignored. @discussion The key in `dictionary` will mapped to the reciever's property name, and the value will set to the property. If the value's type doesn't match the property, this method will try to convert the value based on these rules: `NSString`, `NSNumber` -> c number, such as BOOL, int, long, float, NSUInteger... `NSString` -> NSDate, parsed with format "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd". `NSString` -> NSURL. `NSValue` -> struct or union, such as CGRect, CGSize, ... `NSString` -> SEL, Class. @return Whether succeed. */ - (BOOL)yy_modelSetWithDictionary:(NSDictionary *)dic; /** Generate a json object from the receiver's properties. @return A json object in `NSDictionary` or `NSArray`, or nil if an error occurs. See [NSJSONSerialization isValidJSONObject] for more information. @discussion Any of the invalid property is ignored. If the reciver is `NSArray`, `NSDictionary` or `NSSet`, it just convert the inner object to json object. */ - (nullable id)yy_modelToJSONObject; /** Generate a json string's data from the receiver's properties. @return A json string's data, or nil if an error occurs. @discussion Any of the invalid property is ignored. If the reciver is `NSArray`, `NSDictionary` or `NSSet`, it will also convert the inner object to json string. */ - (nullable NSData *)yy_modelToJSONData; /** Generate a json string from the receiver's properties. @return A json string, or nil if an error occurs. @discussion Any of the invalid property is ignored. If the reciver is `NSArray`, `NSDictionary` or `NSSet`, it will also convert the inner object to json string. */ - (nullable NSString *)yy_modelToJSONString; /** Copy a instance with the receiver's properties. @return A copied instance, or nil if an error occurs. */ - (nullable id)yy_modelCopy; /** Encode the receiver's properties to a coder. @param aCoder An archiver object. */ - (void)yy_modelEncodeWithCoder:(NSCoder *)aCoder; /** Decode the receiver's properties from a decoder. @param aDecoder An archiver object. @return self */ - (id)yy_modelInitWithCoder:(NSCoder *)aDecoder; /** Get a hash code with the receiver's properties. @return Hash code. */ - (NSUInteger)yy_modelHash; /** Compares the receiver with another object for equality, based on properties. @param model Another object. @return `YES` if the reciever is equal to the object, otherwise `NO`. */ - (BOOL)yy_modelIsEqual:(id)model; /** Description method for debugging purposes based on properties. @return A string that describes the contents of the receiver. */ - (NSString *)yy_modelDescription; @end /** Provide some data-model method for NSArray. */ @interface NSArray (YYModel) /** Creates and returns an array from a json-array. This method is thread-safe. @param cls The instance's class in array. @param json A json array of `NSArray`, `NSString` or `NSData`. Example: [{"name","Mary"},{name:"Joe"}] @return A array, or nil if an error occurs. */ + (nullable NSArray *)yy_modelArrayWithClass:(Class)cls json:(id)json; @end /** Provide some data-model method for NSDictionary. */ @interface NSDictionary (YYModel) /** Creates and returns a dictionary from a json. This method is thread-safe. @param cls The value instance's class in dictionary. @param json A json dictionary of `NSDictionary`, `NSString` or `NSData`. Example: {"user1":{"name","Mary"}, "user2": {name:"Joe"}} @return A dictionary, or nil if an error occurs. */ + (nullable NSDictionary *)yy_modelDictionaryWithClass:(Class)cls json:(id)json; @end /** If the default model transform does not fit to your model class, implement one or more method in this protocol to change the default key-value transform process. There's no need to add '<YYModel>' to your class header. */ @protocol YYModel <NSObject> @optional /** Custom property mapper. @discussion If the key in JSON/Dictionary does not match to the model's property name, implements this method and returns the additional mapper. Example: json: { "n":"Harry Pottery", "p": 256, "ext" : { "desc" : "A book written by J.K.Rowling." }, "ID" : 100010 } model: @interface YYBook : NSObject @property NSString *name; @property NSInteger page; @property NSString *desc; @property NSString *bookID; @end @implementation YYBook + (NSDictionary *)modelCustomPropertyMapper { return @{@"name" : @"n", @"page" : @"p", @"desc" : @"ext.desc", @"bookID": @[@"id", @"ID", @"book_id"]}; } @end @return A custom mapper for properties. */ + (nullable NSDictionary<NSString *, id> *)modelCustomPropertyMapper; /** The generic class mapper for container properties. @discussion If the property is a container object, such as NSArray/NSSet/NSDictionary, implements this method and returns a property->class mapper, tells which kind of object will be add to the array/set/dictionary. Example: @class YYShadow, YYBorder, YYAttachment; @interface YYAttributes @property NSString *name; @property NSArray *shadows; @property NSSet *borders; @property NSDictionary *attachments; @end @implementation YYAttributes + (NSDictionary *)modelContainerPropertyGenericClass { return @{@"shadows" : [YYShadow class], @"borders" : YYBorder.class, @"attachments" : @"YYAttachment" }; } @end @return A class mapper. */ + (nullable NSDictionary<NSString *, id> *)modelContainerPropertyGenericClass; /** If you need to create instances of different classes during json->object transform, use the method to choose custom class based on dictionary data. @discussion If the model implements this method, it will be called to determine resulting class during `+modelWithJSON:`, `+modelWithDictionary:`, conveting object of properties of parent objects (both singular and containers via `+modelContainerPropertyGenericClass`). Example: @class YYCircle, YYRectangle, YYLine; @implementation YYShape + (Class)modelCustomClassForDictionary:(NSDictionary*)dictionary { if (dictionary[@"radius"] != nil) { return [YYCircle class]; } else if (dictionary[@"width"] != nil) { return [YYRectangle class]; } else if (dictionary[@"y2"] != nil) { return [YYLine class]; } else { return [self class]; } } @end @param dictionary The json/kv dictionary. @return Class to create from this dictionary, `nil` to use current class. */ + (nullable Class)modelCustomClassForDictionary:(NSDictionary *)dictionary; /** All the properties in blacklist will be ignored in model transform process. Returns nil to ignore this feature. @return An array of property's name. */ + (nullable NSArray<NSString *> *)modelPropertyBlacklist; /** If a property is not in the whitelist, it will be ignored in model transform process. Returns nil to ignore this feature. @return An array of property's name. */ + (nullable NSArray<NSString *> *)modelPropertyWhitelist; /** This method's behavior is similar to `- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic;`, but be called before the model transform. @discussion If the model implements this method, it will be called before `+modelWithJSON:`, `+modelWithDictionary:`, `-modelSetWithJSON:` and `-modelSetWithDictionary:`. If this method returns nil, the transform process will ignore this model. @param dic The json/kv dictionary. @return Returns the modified dictionary, or nil to ignore this model. */ - (NSDictionary *)modelCustomWillTransformFromDictionary:(NSDictionary *)dic; /** If the default json-to-model transform does not fit to your model object, implement this method to do additional process. You can also use this method to validate the model's properties. @discussion If the model implements this method, it will be called at the end of `+modelWithJSON:`, `+modelWithDictionary:`, `-modelSetWithJSON:` and `-modelSetWithDictionary:`. If this method returns NO, the transform process will ignore this model. @param dic The json/kv dictionary. @return Returns YES if the model is valid, or NO to ignore this model. */ - (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic; /** If the default model-to-json transform does not fit to your model class, implement this method to do additional process. You can also use this method to validate the json dictionary. @discussion If the model implements this method, it will be called at the end of `-modelToJSONObject` and `-modelToJSONString`. If this method returns NO, the transform process will ignore this json dictionary. @param dic The json dictionary. @return Returns YES if the model is valid, or NO to ignore this model. */ - (BOOL)modelCustomTransformToDictionary:(NSMutableDictionary *)dic; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/Pods/Headers/Public/YYModel/NSObject+YYModel.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
3,090
```objective-c // // YYClassInfo.m // YYModel <path_to_url // // Created by ibireme on 15/5/9. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // #import "YYClassInfo.h" #import <objc/runtime.h> YYEncodingType YYEncodingGetType(const char *typeEncoding) { char *type = (char *)typeEncoding; if (!type) return YYEncodingTypeUnknown; size_t len = strlen(type); if (len == 0) return YYEncodingTypeUnknown; YYEncodingType qualifier = 0; bool prefix = true; while (prefix) { switch (*type) { case 'r': { qualifier |= YYEncodingTypeQualifierConst; type++; } break; case 'n': { qualifier |= YYEncodingTypeQualifierIn; type++; } break; case 'N': { qualifier |= YYEncodingTypeQualifierInout; type++; } break; case 'o': { qualifier |= YYEncodingTypeQualifierOut; type++; } break; case 'O': { qualifier |= YYEncodingTypeQualifierBycopy; type++; } break; case 'R': { qualifier |= YYEncodingTypeQualifierByref; type++; } break; case 'V': { qualifier |= YYEncodingTypeQualifierOneway; type++; } break; default: { prefix = false; } break; } } len = strlen(type); if (len == 0) return YYEncodingTypeUnknown | qualifier; switch (*type) { case 'v': return YYEncodingTypeVoid | qualifier; case 'B': return YYEncodingTypeBool | qualifier; case 'c': return YYEncodingTypeInt8 | qualifier; case 'C': return YYEncodingTypeUInt8 | qualifier; case 's': return YYEncodingTypeInt16 | qualifier; case 'S': return YYEncodingTypeUInt16 | qualifier; case 'i': return YYEncodingTypeInt32 | qualifier; case 'I': return YYEncodingTypeUInt32 | qualifier; case 'l': return YYEncodingTypeInt32 | qualifier; case 'L': return YYEncodingTypeUInt32 | qualifier; case 'q': return YYEncodingTypeInt64 | qualifier; case 'Q': return YYEncodingTypeUInt64 | qualifier; case 'f': return YYEncodingTypeFloat | qualifier; case 'd': return YYEncodingTypeDouble | qualifier; case 'D': return YYEncodingTypeLongDouble | qualifier; case '#': return YYEncodingTypeClass | qualifier; case ':': return YYEncodingTypeSEL | qualifier; case '*': return YYEncodingTypeCString | qualifier; case '^': return YYEncodingTypePointer | qualifier; case '[': return YYEncodingTypeCArray | qualifier; case '(': return YYEncodingTypeUnion | qualifier; case '{': return YYEncodingTypeStruct | qualifier; case '@': { if (len == 2 && *(type + 1) == '?') return YYEncodingTypeBlock | qualifier; else return YYEncodingTypeObject | qualifier; } default: return YYEncodingTypeUnknown | qualifier; } } @implementation YYClassIvarInfo - (instancetype)initWithIvar:(Ivar)ivar { if (!ivar) return nil; self = [super init]; _ivar = ivar; const char *name = ivar_getName(ivar); if (name) { _name = [NSString stringWithUTF8String:name]; } _offset = ivar_getOffset(ivar); const char *typeEncoding = ivar_getTypeEncoding(ivar); if (typeEncoding) { _typeEncoding = [NSString stringWithUTF8String:typeEncoding]; _type = YYEncodingGetType(typeEncoding); } return self; } @end @implementation YYClassMethodInfo - (instancetype)initWithMethod:(Method)method { if (!method) return nil; self = [super init]; _method = method; _sel = method_getName(method); _imp = method_getImplementation(method); const char *name = sel_getName(_sel); if (name) { _name = [NSString stringWithUTF8String:name]; } const char *typeEncoding = method_getTypeEncoding(method); if (typeEncoding) { _typeEncoding = [NSString stringWithUTF8String:typeEncoding]; } char *returnType = method_copyReturnType(method); if (returnType) { _returnTypeEncoding = [NSString stringWithUTF8String:returnType]; free(returnType); } unsigned int argumentCount = method_getNumberOfArguments(method); if (argumentCount > 0) { NSMutableArray *argumentTypes = [NSMutableArray new]; for (unsigned int i = 0; i < argumentCount; i++) { char *argumentType = method_copyArgumentType(method, i); NSString *type = argumentType ? [NSString stringWithUTF8String:argumentType] : nil; [argumentTypes addObject:type ? type : @""]; if (argumentType) free(argumentType); } _argumentTypeEncodings = argumentTypes; } return self; } @end @implementation YYClassPropertyInfo - (instancetype)initWithProperty:(objc_property_t)property { if (!property) return nil; self = [super init]; _property = property; const char *name = property_getName(property); if (name) { _name = [NSString stringWithUTF8String:name]; } YYEncodingType type = 0; unsigned int attrCount; objc_property_attribute_t *attrs = property_copyAttributeList(property, &attrCount); for (unsigned int i = 0; i < attrCount; i++) { switch (attrs[i].name[0]) { case 'T': { // Type encoding if (attrs[i].value) { _typeEncoding = [NSString stringWithUTF8String:attrs[i].value]; type = YYEncodingGetType(attrs[i].value); if ((type & YYEncodingTypeMask) == YYEncodingTypeObject && _typeEncoding.length) { NSScanner *scanner = [NSScanner scannerWithString:_typeEncoding]; if (![scanner scanString:@"@\"" intoString:NULL]) continue; NSString *clsName = nil; if ([scanner scanUpToCharactersFromSet: [NSCharacterSet characterSetWithCharactersInString:@"\"<"] intoString:&clsName]) { if (clsName.length) _cls = objc_getClass(clsName.UTF8String); } NSMutableArray *protocols = nil; while ([scanner scanString:@"<" intoString:NULL]) { NSString* protocol = nil; if ([scanner scanUpToString:@">" intoString: &protocol]) { if (protocol.length) { if (!protocols) protocols = [NSMutableArray new]; [protocols addObject:protocol]; } } [scanner scanString:@">" intoString:NULL]; } _protocols = protocols; } } } break; case 'V': { // Instance variable if (attrs[i].value) { _ivarName = [NSString stringWithUTF8String:attrs[i].value]; } } break; case 'R': { type |= YYEncodingTypePropertyReadonly; } break; case 'C': { type |= YYEncodingTypePropertyCopy; } break; case '&': { type |= YYEncodingTypePropertyRetain; } break; case 'N': { type |= YYEncodingTypePropertyNonatomic; } break; case 'D': { type |= YYEncodingTypePropertyDynamic; } break; case 'W': { type |= YYEncodingTypePropertyWeak; } break; case 'G': { type |= YYEncodingTypePropertyCustomGetter; if (attrs[i].value) { _getter = NSSelectorFromString([NSString stringWithUTF8String:attrs[i].value]); } } break; case 'S': { type |= YYEncodingTypePropertyCustomSetter; if (attrs[i].value) { _setter = NSSelectorFromString([NSString stringWithUTF8String:attrs[i].value]); } } // break; commented for code coverage in next line default: break; } } if (attrs) { free(attrs); attrs = NULL; } _type = type; if (_name.length) { if (!_getter) { _getter = NSSelectorFromString(_name); } if (!_setter) { _setter = NSSelectorFromString([NSString stringWithFormat:@"set%@%@:", [_name substringToIndex:1].uppercaseString, [_name substringFromIndex:1]]); } } return self; } @end @implementation YYClassInfo { BOOL _needUpdate; } - (instancetype)initWithClass:(Class)cls { if (!cls) return nil; self = [super init]; _cls = cls; _superCls = class_getSuperclass(cls); _isMeta = class_isMetaClass(cls); if (!_isMeta) { _metaCls = objc_getMetaClass(class_getName(cls)); } _name = NSStringFromClass(cls); [self _update]; _superClassInfo = [self.class classInfoWithClass:_superCls]; return self; } - (void)_update { _ivarInfos = nil; _methodInfos = nil; _propertyInfos = nil; Class cls = self.cls; unsigned int methodCount = 0; Method *methods = class_copyMethodList(cls, &methodCount); if (methods) { NSMutableDictionary *methodInfos = [NSMutableDictionary new]; _methodInfos = methodInfos; for (unsigned int i = 0; i < methodCount; i++) { YYClassMethodInfo *info = [[YYClassMethodInfo alloc] initWithMethod:methods[i]]; if (info.name) methodInfos[info.name] = info; } free(methods); } unsigned int propertyCount = 0; objc_property_t *properties = class_copyPropertyList(cls, &propertyCount); if (properties) { NSMutableDictionary *propertyInfos = [NSMutableDictionary new]; _propertyInfos = propertyInfos; for (unsigned int i = 0; i < propertyCount; i++) { YYClassPropertyInfo *info = [[YYClassPropertyInfo alloc] initWithProperty:properties[i]]; if (info.name) propertyInfos[info.name] = info; } free(properties); } unsigned int ivarCount = 0; Ivar *ivars = class_copyIvarList(cls, &ivarCount); if (ivars) { NSMutableDictionary *ivarInfos = [NSMutableDictionary new]; _ivarInfos = ivarInfos; for (unsigned int i = 0; i < ivarCount; i++) { YYClassIvarInfo *info = [[YYClassIvarInfo alloc] initWithIvar:ivars[i]]; if (info.name) ivarInfos[info.name] = info; } free(ivars); } if (!_ivarInfos) _ivarInfos = @{}; if (!_methodInfos) _methodInfos = @{}; if (!_propertyInfos) _propertyInfos = @{}; _needUpdate = NO; } - (void)setNeedUpdate { _needUpdate = YES; } - (BOOL)needUpdate { return _needUpdate; } + (instancetype)classInfoWithClass:(Class)cls { if (!cls) return nil; static CFMutableDictionaryRef classCache; static CFMutableDictionaryRef metaCache; static dispatch_once_t onceToken; static dispatch_semaphore_t lock; dispatch_once(&onceToken, ^{ classCache = CFDictionaryCreateMutable(CFAllocatorGetDefault(), 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); metaCache = CFDictionaryCreateMutable(CFAllocatorGetDefault(), 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); lock = dispatch_semaphore_create(1); }); dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER); YYClassInfo *info = CFDictionaryGetValue(class_isMetaClass(cls) ? metaCache : classCache, (__bridge const void *)(cls)); if (info && info->_needUpdate) { [info _update]; } dispatch_semaphore_signal(lock); if (!info) { info = [[YYClassInfo alloc] initWithClass:cls]; if (info) { dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER); CFDictionarySetValue(info.isMeta ? metaCache : classCache, (__bridge const void *)(cls), (__bridge const void *)(info)); dispatch_semaphore_signal(lock); } } return info; } + (instancetype)classInfoWithClassName:(NSString *)className { Class cls = NSClassFromString(className); return [self classInfoWithClass:cls]; } @end ```
/content/code_sandbox/Pods/YYModel/YYModel/YYClassInfo.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,829
```html <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>hello World</title> </head> <script type="text/javascript"> function JSCallOc1(){ test1(); } function JSCallOc2(){ test2('','iOS'); } function aaa(){ alert("OCjs"); } function bbb(name,num){ alert(name+num); } </script> <body bgcolor="#555555"> <button type="button" onclick="JSCallOc1()">JSOC()</button> <button type="button" onclick="JSCallOc2()">JSOC()</button> </body> </html> ```
/content/code_sandbox/BigShow1949/Test.html
html
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
162
```objective-c // // NSObject+YYModel.m // YYModel <path_to_url // // Created by ibireme on 15/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 "NSObject+YYModel.h" #import "YYClassInfo.h" #import <objc/message.h> #define force_inline __inline__ __attribute__((always_inline)) /// Foundation Class Type typedef NS_ENUM (NSUInteger, YYEncodingNSType) { YYEncodingTypeNSUnknown = 0, YYEncodingTypeNSString, YYEncodingTypeNSMutableString, YYEncodingTypeNSValue, YYEncodingTypeNSNumber, YYEncodingTypeNSDecimalNumber, YYEncodingTypeNSData, YYEncodingTypeNSMutableData, YYEncodingTypeNSDate, YYEncodingTypeNSURL, YYEncodingTypeNSArray, YYEncodingTypeNSMutableArray, YYEncodingTypeNSDictionary, YYEncodingTypeNSMutableDictionary, YYEncodingTypeNSSet, YYEncodingTypeNSMutableSet, }; /// Get the Foundation class type from property info. static force_inline YYEncodingNSType YYClassGetNSType(Class cls) { if (!cls) return YYEncodingTypeNSUnknown; if ([cls isSubclassOfClass:[NSMutableString class]]) return YYEncodingTypeNSMutableString; if ([cls isSubclassOfClass:[NSString class]]) return YYEncodingTypeNSString; if ([cls isSubclassOfClass:[NSDecimalNumber class]]) return YYEncodingTypeNSDecimalNumber; if ([cls isSubclassOfClass:[NSNumber class]]) return YYEncodingTypeNSNumber; if ([cls isSubclassOfClass:[NSValue class]]) return YYEncodingTypeNSValue; if ([cls isSubclassOfClass:[NSMutableData class]]) return YYEncodingTypeNSMutableData; if ([cls isSubclassOfClass:[NSData class]]) return YYEncodingTypeNSData; if ([cls isSubclassOfClass:[NSDate class]]) return YYEncodingTypeNSDate; if ([cls isSubclassOfClass:[NSURL class]]) return YYEncodingTypeNSURL; if ([cls isSubclassOfClass:[NSMutableArray class]]) return YYEncodingTypeNSMutableArray; if ([cls isSubclassOfClass:[NSArray class]]) return YYEncodingTypeNSArray; if ([cls isSubclassOfClass:[NSMutableDictionary class]]) return YYEncodingTypeNSMutableDictionary; if ([cls isSubclassOfClass:[NSDictionary class]]) return YYEncodingTypeNSDictionary; if ([cls isSubclassOfClass:[NSMutableSet class]]) return YYEncodingTypeNSMutableSet; if ([cls isSubclassOfClass:[NSSet class]]) return YYEncodingTypeNSSet; return YYEncodingTypeNSUnknown; } /// Whether the type is c number. static force_inline BOOL YYEncodingTypeIsCNumber(YYEncodingType type) { switch (type & YYEncodingTypeMask) { case YYEncodingTypeBool: case YYEncodingTypeInt8: case YYEncodingTypeUInt8: case YYEncodingTypeInt16: case YYEncodingTypeUInt16: case YYEncodingTypeInt32: case YYEncodingTypeUInt32: case YYEncodingTypeInt64: case YYEncodingTypeUInt64: case YYEncodingTypeFloat: case YYEncodingTypeDouble: case YYEncodingTypeLongDouble: return YES; default: return NO; } } /// Parse a number value from 'id'. static force_inline NSNumber *YYNSNumberCreateFromID(__unsafe_unretained id value) { static NSCharacterSet *dot; static NSDictionary *dic; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ dot = [NSCharacterSet characterSetWithRange:NSMakeRange('.', 1)]; dic = @{@"TRUE" : @(YES), @"True" : @(YES), @"true" : @(YES), @"FALSE" : @(NO), @"False" : @(NO), @"false" : @(NO), @"YES" : @(YES), @"Yes" : @(YES), @"yes" : @(YES), @"NO" : @(NO), @"No" : @(NO), @"no" : @(NO), @"NIL" : (id)kCFNull, @"Nil" : (id)kCFNull, @"nil" : (id)kCFNull, @"NULL" : (id)kCFNull, @"Null" : (id)kCFNull, @"null" : (id)kCFNull, @"(NULL)" : (id)kCFNull, @"(Null)" : (id)kCFNull, @"(null)" : (id)kCFNull, @"<NULL>" : (id)kCFNull, @"<Null>" : (id)kCFNull, @"<null>" : (id)kCFNull}; }); if (!value || value == (id)kCFNull) return nil; if ([value isKindOfClass:[NSNumber class]]) return value; if ([value isKindOfClass:[NSString class]]) { NSNumber *num = dic[value]; if (num) { if (num == (id)kCFNull) return nil; return num; } if ([(NSString *)value rangeOfCharacterFromSet:dot].location != NSNotFound) { const char *cstring = ((NSString *)value).UTF8String; if (!cstring) return nil; double num = atof(cstring); if (isnan(num) || isinf(num)) return nil; return @(num); } else { const char *cstring = ((NSString *)value).UTF8String; if (!cstring) return nil; return @(atoll(cstring)); } } return nil; } /// Parse string to date. static force_inline NSDate *YYNSDateFromString(__unsafe_unretained NSString *string) { typedef NSDate* (^YYNSDateParseBlock)(NSString *string); #define kParserNum 34 static YYNSDateParseBlock blocks[kParserNum + 1] = {0}; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ { /* 2014-01-20 // Google */ NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; formatter.dateFormat = @"yyyy-MM-dd"; blocks[10] = ^(NSString *string) { return [formatter dateFromString:string]; }; } { /* 2014-01-20 12:24:48 2014-01-20T12:24:48 // Google 2014-01-20 12:24:48.000 2014-01-20T12:24:48.000 */ NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init]; formatter1.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter1.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; formatter1.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss"; NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init]; formatter2.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter2.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; formatter2.dateFormat = @"yyyy-MM-dd HH:mm:ss"; NSDateFormatter *formatter3 = [[NSDateFormatter alloc] init]; formatter3.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter3.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; formatter3.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS"; NSDateFormatter *formatter4 = [[NSDateFormatter alloc] init]; formatter4.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter4.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; formatter4.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS"; blocks[19] = ^(NSString *string) { if ([string characterAtIndex:10] == 'T') { return [formatter1 dateFromString:string]; } else { return [formatter2 dateFromString:string]; } }; blocks[23] = ^(NSString *string) { if ([string characterAtIndex:10] == 'T') { return [formatter3 dateFromString:string]; } else { return [formatter4 dateFromString:string]; } }; } { /* 2014-01-20T12:24:48Z // Github, Apple 2014-01-20T12:24:48+0800 // Facebook 2014-01-20T12:24:48+12:00 // Google 2014-01-20T12:24:48.000Z 2014-01-20T12:24:48.000+0800 2014-01-20T12:24:48.000+12:00 */ NSDateFormatter *formatter = [NSDateFormatter new]; formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ"; NSDateFormatter *formatter2 = [NSDateFormatter new]; formatter2.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter2.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ"; blocks[20] = ^(NSString *string) { return [formatter dateFromString:string]; }; blocks[24] = ^(NSString *string) { return [formatter dateFromString:string]?: [formatter2 dateFromString:string]; }; blocks[25] = ^(NSString *string) { return [formatter dateFromString:string]; }; blocks[28] = ^(NSString *string) { return [formatter2 dateFromString:string]; }; blocks[29] = ^(NSString *string) { return [formatter2 dateFromString:string]; }; } { /* Fri Sep 04 00:12:21 +0800 2015 // Weibo, Twitter Fri Sep 04 00:12:21.000 +0800 2015 */ NSDateFormatter *formatter = [NSDateFormatter new]; formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy"; NSDateFormatter *formatter2 = [NSDateFormatter new]; formatter2.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; formatter2.dateFormat = @"EEE MMM dd HH:mm:ss.SSS Z yyyy"; blocks[30] = ^(NSString *string) { return [formatter dateFromString:string]; }; blocks[34] = ^(NSString *string) { return [formatter2 dateFromString:string]; }; } }); if (!string) return nil; if (string.length > kParserNum) return nil; YYNSDateParseBlock parser = blocks[string.length]; if (!parser) return nil; return parser(string); #undef kParserNum } /// Get the 'NSBlock' class. static force_inline Class YYNSBlockClass() { static Class cls; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ void (^block)(void) = ^{}; cls = ((NSObject *)block).class; while (class_getSuperclass(cls) != [NSObject class]) { cls = class_getSuperclass(cls); } }); return cls; // current is "NSBlock" } /** Get the ISO date formatter. ISO8601 format example: 2010-07-09T16:13:30+12:00 2011-01-11T11:11:11+0000 2011-01-26T19:06:43Z length: 20/24/25 */ static force_inline NSDateFormatter *YYISODateFormatter() { 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; } /// Get the value with key paths from dictionary /// The dic should be NSDictionary, and the keyPath should not be nil. static force_inline id YYValueForKeyPath(__unsafe_unretained NSDictionary *dic, __unsafe_unretained NSArray *keyPaths) { id value = nil; for (NSUInteger i = 0, max = keyPaths.count; i < max; i++) { value = dic[keyPaths[i]]; if (i + 1 < max) { if ([value isKindOfClass:[NSDictionary class]]) { dic = value; } else { return nil; } } } return value; } /// Get the value with multi key (or key path) from dictionary /// The dic should be NSDictionary static force_inline id YYValueForMultiKeys(__unsafe_unretained NSDictionary *dic, __unsafe_unretained NSArray *multiKeys) { id value = nil; for (NSString *key in multiKeys) { if ([key isKindOfClass:[NSString class]]) { value = dic[key]; if (value) break; } else { value = YYValueForKeyPath(dic, (NSArray *)key); if (value) break; } } return value; } /// A property info in object model. @interface _YYModelPropertyMeta : NSObject { @package NSString *_name; ///< property's name YYEncodingType _type; ///< property's type YYEncodingNSType _nsType; ///< property's Foundation type BOOL _isCNumber; ///< is c number type Class _cls; ///< property's class, or nil Class _genericCls; ///< container's generic class, or nil if threr's no generic class SEL _getter; ///< getter, or nil if the instances cannot respond SEL _setter; ///< setter, or nil if the instances cannot respond BOOL _isKVCCompatible; ///< YES if it can access with key-value coding BOOL _isStructAvailableForKeyedArchiver; ///< YES if the struct can encoded with keyed archiver/unarchiver BOOL _hasCustomClassFromDictionary; ///< class/generic class implements +modelCustomClassForDictionary: /* property->key: _mappedToKey:key _mappedToKeyPath:nil _mappedToKeyArray:nil property->keyPath: _mappedToKey:keyPath _mappedToKeyPath:keyPath(array) _mappedToKeyArray:nil property->keys: _mappedToKey:keys[0] _mappedToKeyPath:nil/keyPath _mappedToKeyArray:keys(array) */ NSString *_mappedToKey; ///< the key mapped to NSArray *_mappedToKeyPath; ///< the key path mapped to (nil if the name is not key path) NSArray *_mappedToKeyArray; ///< the key(NSString) or keyPath(NSArray) array (nil if not mapped to multiple keys) YYClassPropertyInfo *_info; ///< property's info _YYModelPropertyMeta *_next; ///< next meta if there are multiple properties mapped to the same key. } @end @implementation _YYModelPropertyMeta + (instancetype)metaWithClassInfo:(YYClassInfo *)classInfo propertyInfo:(YYClassPropertyInfo *)propertyInfo generic:(Class)generic { // support pseudo generic class with protocol name if (!generic && propertyInfo.protocols) { for (NSString *protocol in propertyInfo.protocols) { Class cls = objc_getClass(protocol.UTF8String); if (cls) { generic = cls; break; } } } _YYModelPropertyMeta *meta = [self new]; meta->_name = propertyInfo.name; meta->_type = propertyInfo.type; meta->_info = propertyInfo; meta->_genericCls = generic; if ((meta->_type & YYEncodingTypeMask) == YYEncodingTypeObject) { meta->_nsType = YYClassGetNSType(propertyInfo.cls); } else { meta->_isCNumber = YYEncodingTypeIsCNumber(meta->_type); } if ((meta->_type & YYEncodingTypeMask) == YYEncodingTypeStruct) { /* It seems that NSKeyedUnarchiver cannot decode NSValue except these structs: */ static NSSet *types = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSMutableSet *set = [NSMutableSet new]; // 32 bit [set addObject:@"{CGSize=ff}"]; [set addObject:@"{CGPoint=ff}"]; [set addObject:@"{CGRect={CGPoint=ff}{CGSize=ff}}"]; [set addObject:@"{CGAffineTransform=ffffff}"]; [set addObject:@"{UIEdgeInsets=ffff}"]; [set addObject:@"{UIOffset=ff}"]; // 64 bit [set addObject:@"{CGSize=dd}"]; [set addObject:@"{CGPoint=dd}"]; [set addObject:@"{CGRect={CGPoint=dd}{CGSize=dd}}"]; [set addObject:@"{CGAffineTransform=dddddd}"]; [set addObject:@"{UIEdgeInsets=dddd}"]; [set addObject:@"{UIOffset=dd}"]; types = set; }); if ([types containsObject:propertyInfo.typeEncoding]) { meta->_isStructAvailableForKeyedArchiver = YES; } } meta->_cls = propertyInfo.cls; if (generic) { meta->_hasCustomClassFromDictionary = [generic respondsToSelector:@selector(modelCustomClassForDictionary:)]; } else if (meta->_cls && meta->_nsType == YYEncodingTypeNSUnknown) { meta->_hasCustomClassFromDictionary = [meta->_cls respondsToSelector:@selector(modelCustomClassForDictionary:)]; } if (propertyInfo.getter) { if ([classInfo.cls instancesRespondToSelector:propertyInfo.getter]) { meta->_getter = propertyInfo.getter; } } if (propertyInfo.setter) { if ([classInfo.cls instancesRespondToSelector:propertyInfo.setter]) { meta->_setter = propertyInfo.setter; } } if (meta->_getter && meta->_setter) { /* KVC invalid type: long double pointer (such as SEL/CoreFoundation object) */ switch (meta->_type & YYEncodingTypeMask) { case YYEncodingTypeBool: case YYEncodingTypeInt8: case YYEncodingTypeUInt8: case YYEncodingTypeInt16: case YYEncodingTypeUInt16: case YYEncodingTypeInt32: case YYEncodingTypeUInt32: case YYEncodingTypeInt64: case YYEncodingTypeUInt64: case YYEncodingTypeFloat: case YYEncodingTypeDouble: case YYEncodingTypeObject: case YYEncodingTypeClass: case YYEncodingTypeBlock: case YYEncodingTypeStruct: case YYEncodingTypeUnion: { meta->_isKVCCompatible = YES; } break; default: break; } } return meta; } @end /// A class info in object model. @interface _YYModelMeta : NSObject { @package YYClassInfo *_classInfo; /// Key:mapped key and key path, Value:_YYModelPropertyMeta. NSDictionary *_mapper; /// Array<_YYModelPropertyMeta>, all property meta of this model. NSArray *_allPropertyMetas; /// Array<_YYModelPropertyMeta>, property meta which is mapped to a key path. NSArray *_keyPathPropertyMetas; /// Array<_YYModelPropertyMeta>, property meta which is mapped to multi keys. NSArray *_multiKeysPropertyMetas; /// The number of mapped key (and key path), same to _mapper.count. NSUInteger _keyMappedCount; /// Model class type. YYEncodingNSType _nsType; BOOL _hasCustomWillTransformFromDictionary; BOOL _hasCustomTransformFromDictionary; BOOL _hasCustomTransformToDictionary; BOOL _hasCustomClassFromDictionary; } @end @implementation _YYModelMeta - (instancetype)initWithClass:(Class)cls { YYClassInfo *classInfo = [YYClassInfo classInfoWithClass:cls]; if (!classInfo) return nil; self = [super init]; // Get black list NSSet *blacklist = nil; if ([cls respondsToSelector:@selector(modelPropertyBlacklist)]) { NSArray *properties = [(id<YYModel>)cls modelPropertyBlacklist]; if (properties) { blacklist = [NSSet setWithArray:properties]; } } // Get white list NSSet *whitelist = nil; if ([cls respondsToSelector:@selector(modelPropertyWhitelist)]) { NSArray *properties = [(id<YYModel>)cls modelPropertyWhitelist]; if (properties) { whitelist = [NSSet setWithArray:properties]; } } // Get container property's generic class NSDictionary *genericMapper = nil; if ([cls respondsToSelector:@selector(modelContainerPropertyGenericClass)]) { genericMapper = [(id<YYModel>)cls modelContainerPropertyGenericClass]; if (genericMapper) { NSMutableDictionary *tmp = [NSMutableDictionary new]; [genericMapper enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { if (![key isKindOfClass:[NSString class]]) return; Class meta = object_getClass(obj); if (!meta) return; if (class_isMetaClass(meta)) { tmp[key] = obj; } else if ([obj isKindOfClass:[NSString class]]) { Class cls = NSClassFromString(obj); if (cls) { tmp[key] = cls; } } }]; genericMapper = tmp; } } // Create all property metas. NSMutableDictionary *allPropertyMetas = [NSMutableDictionary new]; YYClassInfo *curClassInfo = classInfo; while (curClassInfo && curClassInfo.superCls != nil) { // recursive parse super class, but ignore root class (NSObject/NSProxy) for (YYClassPropertyInfo *propertyInfo in curClassInfo.propertyInfos.allValues) { if (!propertyInfo.name) continue; if (blacklist && [blacklist containsObject:propertyInfo.name]) continue; if (whitelist && ![whitelist containsObject:propertyInfo.name]) continue; _YYModelPropertyMeta *meta = [_YYModelPropertyMeta metaWithClassInfo:classInfo propertyInfo:propertyInfo generic:genericMapper[propertyInfo.name]]; if (!meta || !meta->_name) continue; if (!meta->_getter || !meta->_setter) continue; if (allPropertyMetas[meta->_name]) continue; allPropertyMetas[meta->_name] = meta; } curClassInfo = curClassInfo.superClassInfo; } if (allPropertyMetas.count) _allPropertyMetas = allPropertyMetas.allValues.copy; // create mapper NSMutableDictionary *mapper = [NSMutableDictionary new]; NSMutableArray *keyPathPropertyMetas = [NSMutableArray new]; NSMutableArray *multiKeysPropertyMetas = [NSMutableArray new]; if ([cls respondsToSelector:@selector(modelCustomPropertyMapper)]) { NSDictionary *customMapper = [(id <YYModel>)cls modelCustomPropertyMapper]; [customMapper enumerateKeysAndObjectsUsingBlock:^(NSString *propertyName, NSString *mappedToKey, BOOL *stop) { _YYModelPropertyMeta *propertyMeta = allPropertyMetas[propertyName]; if (!propertyMeta) return; [allPropertyMetas removeObjectForKey:propertyName]; if ([mappedToKey isKindOfClass:[NSString class]]) { if (mappedToKey.length == 0) return; propertyMeta->_mappedToKey = mappedToKey; NSArray *keyPath = [mappedToKey componentsSeparatedByString:@"."]; for (NSString *onePath in keyPath) { if (onePath.length == 0) { NSMutableArray *tmp = keyPath.mutableCopy; [tmp removeObject:@""]; keyPath = tmp; break; } } if (keyPath.count > 1) { propertyMeta->_mappedToKeyPath = keyPath; [keyPathPropertyMetas addObject:propertyMeta]; } propertyMeta->_next = mapper[mappedToKey] ?: nil; mapper[mappedToKey] = propertyMeta; } else if ([mappedToKey isKindOfClass:[NSArray class]]) { NSMutableArray *mappedToKeyArray = [NSMutableArray new]; for (NSString *oneKey in ((NSArray *)mappedToKey)) { if (![oneKey isKindOfClass:[NSString class]]) continue; if (oneKey.length == 0) continue; NSArray *keyPath = [oneKey componentsSeparatedByString:@"."]; if (keyPath.count > 1) { [mappedToKeyArray addObject:keyPath]; } else { [mappedToKeyArray addObject:oneKey]; } if (!propertyMeta->_mappedToKey) { propertyMeta->_mappedToKey = oneKey; propertyMeta->_mappedToKeyPath = keyPath.count > 1 ? keyPath : nil; } } if (!propertyMeta->_mappedToKey) return; propertyMeta->_mappedToKeyArray = mappedToKeyArray; [multiKeysPropertyMetas addObject:propertyMeta]; propertyMeta->_next = mapper[mappedToKey] ?: nil; mapper[mappedToKey] = propertyMeta; } }]; } [allPropertyMetas enumerateKeysAndObjectsUsingBlock:^(NSString *name, _YYModelPropertyMeta *propertyMeta, BOOL *stop) { propertyMeta->_mappedToKey = name; propertyMeta->_next = mapper[name] ?: nil; mapper[name] = propertyMeta; }]; if (mapper.count) _mapper = mapper; if (keyPathPropertyMetas) _keyPathPropertyMetas = keyPathPropertyMetas; if (multiKeysPropertyMetas) _multiKeysPropertyMetas = multiKeysPropertyMetas; _classInfo = classInfo; _keyMappedCount = _allPropertyMetas.count; _nsType = YYClassGetNSType(cls); _hasCustomWillTransformFromDictionary = ([cls instancesRespondToSelector:@selector(modelCustomWillTransformFromDictionary:)]); _hasCustomTransformFromDictionary = ([cls instancesRespondToSelector:@selector(modelCustomTransformFromDictionary:)]); _hasCustomTransformToDictionary = ([cls instancesRespondToSelector:@selector(modelCustomTransformToDictionary:)]); _hasCustomClassFromDictionary = ([cls respondsToSelector:@selector(modelCustomClassForDictionary:)]); return self; } /// Returns the cached model class meta + (instancetype)metaWithClass:(Class)cls { if (!cls) return nil; static CFMutableDictionaryRef cache; static dispatch_once_t onceToken; static dispatch_semaphore_t lock; dispatch_once(&onceToken, ^{ cache = CFDictionaryCreateMutable(CFAllocatorGetDefault(), 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); lock = dispatch_semaphore_create(1); }); dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER); _YYModelMeta *meta = CFDictionaryGetValue(cache, (__bridge const void *)(cls)); dispatch_semaphore_signal(lock); if (!meta || meta->_classInfo.needUpdate) { meta = [[_YYModelMeta alloc] initWithClass:cls]; if (meta) { dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER); CFDictionarySetValue(cache, (__bridge const void *)(cls), (__bridge const void *)(meta)); dispatch_semaphore_signal(lock); } } return meta; } @end /** Get number from property. @discussion Caller should hold strong reference to the parameters before this function returns. @param model Should not be nil. @param meta Should not be nil, meta.isCNumber should be YES, meta.getter should not be nil. @return A number object, or nil if failed. */ static force_inline NSNumber *ModelCreateNumberFromProperty(__unsafe_unretained id model, __unsafe_unretained _YYModelPropertyMeta *meta) { switch (meta->_type & YYEncodingTypeMask) { case YYEncodingTypeBool: { return @(((bool (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter)); } case YYEncodingTypeInt8: { return @(((int8_t (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter)); } case YYEncodingTypeUInt8: { return @(((uint8_t (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter)); } case YYEncodingTypeInt16: { return @(((int16_t (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter)); } case YYEncodingTypeUInt16: { return @(((uint16_t (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter)); } case YYEncodingTypeInt32: { return @(((int32_t (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter)); } case YYEncodingTypeUInt32: { return @(((uint32_t (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter)); } case YYEncodingTypeInt64: { return @(((int64_t (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter)); } case YYEncodingTypeUInt64: { return @(((uint64_t (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter)); } case YYEncodingTypeFloat: { float num = ((float (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter); if (isnan(num) || isinf(num)) return nil; return @(num); } case YYEncodingTypeDouble: { double num = ((double (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter); if (isnan(num) || isinf(num)) return nil; return @(num); } case YYEncodingTypeLongDouble: { double num = ((long double (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter); if (isnan(num) || isinf(num)) return nil; return @(num); } default: return nil; } } /** Set number to property. @discussion Caller should hold strong reference to the parameters before this function returns. @param model Should not be nil. @param num Can be nil. @param meta Should not be nil, meta.isCNumber should be YES, meta.setter should not be nil. */ static force_inline void ModelSetNumberToProperty(__unsafe_unretained id model, __unsafe_unretained NSNumber *num, __unsafe_unretained _YYModelPropertyMeta *meta) { switch (meta->_type & YYEncodingTypeMask) { case YYEncodingTypeBool: { ((void (*)(id, SEL, bool))(void *) objc_msgSend)((id)model, meta->_setter, num.boolValue); } break; case YYEncodingTypeInt8: { ((void (*)(id, SEL, int8_t))(void *) objc_msgSend)((id)model, meta->_setter, (int8_t)num.charValue); } break; case YYEncodingTypeUInt8: { ((void (*)(id, SEL, uint8_t))(void *) objc_msgSend)((id)model, meta->_setter, (uint8_t)num.unsignedCharValue); } break; case YYEncodingTypeInt16: { ((void (*)(id, SEL, int16_t))(void *) objc_msgSend)((id)model, meta->_setter, (int16_t)num.shortValue); } break; case YYEncodingTypeUInt16: { ((void (*)(id, SEL, uint16_t))(void *) objc_msgSend)((id)model, meta->_setter, (uint16_t)num.unsignedShortValue); } break; case YYEncodingTypeInt32: { ((void (*)(id, SEL, int32_t))(void *) objc_msgSend)((id)model, meta->_setter, (int32_t)num.intValue); } case YYEncodingTypeUInt32: { ((void (*)(id, SEL, uint32_t))(void *) objc_msgSend)((id)model, meta->_setter, (uint32_t)num.unsignedIntValue); } break; case YYEncodingTypeInt64: { if ([num isKindOfClass:[NSDecimalNumber class]]) { ((void (*)(id, SEL, int64_t))(void *) objc_msgSend)((id)model, meta->_setter, (int64_t)num.stringValue.longLongValue); } else { ((void (*)(id, SEL, uint64_t))(void *) objc_msgSend)((id)model, meta->_setter, (uint64_t)num.longLongValue); } } break; case YYEncodingTypeUInt64: { if ([num isKindOfClass:[NSDecimalNumber class]]) { ((void (*)(id, SEL, int64_t))(void *) objc_msgSend)((id)model, meta->_setter, (int64_t)num.stringValue.longLongValue); } else { ((void (*)(id, SEL, uint64_t))(void *) objc_msgSend)((id)model, meta->_setter, (uint64_t)num.unsignedLongLongValue); } } break; case YYEncodingTypeFloat: { float f = num.floatValue; if (isnan(f) || isinf(f)) f = 0; ((void (*)(id, SEL, float))(void *) objc_msgSend)((id)model, meta->_setter, f); } break; case YYEncodingTypeDouble: { double d = num.doubleValue; if (isnan(d) || isinf(d)) d = 0; ((void (*)(id, SEL, double))(void *) objc_msgSend)((id)model, meta->_setter, d); } break; case YYEncodingTypeLongDouble: { long double d = num.doubleValue; if (isnan(d) || isinf(d)) d = 0; ((void (*)(id, SEL, long double))(void *) objc_msgSend)((id)model, meta->_setter, (long double)d); } // break; commented for code coverage in next line default: break; } } /** Set value to model with a property meta. @discussion Caller should hold strong reference to the parameters before this function returns. @param model Should not be nil. @param value Should not be nil, but can be NSNull. @param meta Should not be nil, and meta->_setter should not be nil. */ static void ModelSetValueForProperty(__unsafe_unretained id model, __unsafe_unretained id value, __unsafe_unretained _YYModelPropertyMeta *meta) { if (meta->_isCNumber) { NSNumber *num = YYNSNumberCreateFromID(value); ModelSetNumberToProperty(model, num, meta); if (num) [num class]; // hold the number } else if (meta->_nsType) { if (value == (id)kCFNull) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, (id)nil); } else { switch (meta->_nsType) { case YYEncodingTypeNSString: case YYEncodingTypeNSMutableString: { if ([value isKindOfClass:[NSString class]]) { if (meta->_nsType == YYEncodingTypeNSString) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, value); } else { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, ((NSString *)value).mutableCopy); } } else if ([value isKindOfClass:[NSNumber class]]) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, (meta->_nsType == YYEncodingTypeNSString) ? ((NSNumber *)value).stringValue : ((NSNumber *)value).stringValue.mutableCopy); } else if ([value isKindOfClass:[NSData class]]) { NSMutableString *string = [[NSMutableString alloc] initWithData:value encoding:NSUTF8StringEncoding]; ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, string); } else if ([value isKindOfClass:[NSURL class]]) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, (meta->_nsType == YYEncodingTypeNSString) ? ((NSURL *)value).absoluteString : ((NSURL *)value).absoluteString.mutableCopy); } else if ([value isKindOfClass:[NSAttributedString class]]) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, (meta->_nsType == YYEncodingTypeNSString) ? ((NSAttributedString *)value).string : ((NSAttributedString *)value).string.mutableCopy); } } break; case YYEncodingTypeNSValue: case YYEncodingTypeNSNumber: case YYEncodingTypeNSDecimalNumber: { if (meta->_nsType == YYEncodingTypeNSNumber) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, YYNSNumberCreateFromID(value)); } else if (meta->_nsType == YYEncodingTypeNSDecimalNumber) { if ([value isKindOfClass:[NSDecimalNumber class]]) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, value); } else if ([value isKindOfClass:[NSNumber class]]) { NSDecimalNumber *decNum = [NSDecimalNumber decimalNumberWithDecimal:[((NSNumber *)value) decimalValue]]; ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, decNum); } else if ([value isKindOfClass:[NSString class]]) { NSDecimalNumber *decNum = [NSDecimalNumber decimalNumberWithString:value]; NSDecimal dec = decNum.decimalValue; if (dec._length == 0 && dec._isNegative) { decNum = nil; // NaN } ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, decNum); } } else { // YYEncodingTypeNSValue if ([value isKindOfClass:[NSValue class]]) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, value); } } } break; case YYEncodingTypeNSData: case YYEncodingTypeNSMutableData: { if ([value isKindOfClass:[NSData class]]) { if (meta->_nsType == YYEncodingTypeNSData) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, value); } else { NSMutableData *data = ((NSData *)value).mutableCopy; ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, data); } } else if ([value isKindOfClass:[NSString class]]) { NSData *data = [(NSString *)value dataUsingEncoding:NSUTF8StringEncoding]; if (meta->_nsType == YYEncodingTypeNSMutableData) { data = ((NSData *)data).mutableCopy; } ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, data); } } break; case YYEncodingTypeNSDate: { if ([value isKindOfClass:[NSDate class]]) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, value); } else if ([value isKindOfClass:[NSString class]]) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, YYNSDateFromString(value)); } } break; case YYEncodingTypeNSURL: { if ([value isKindOfClass:[NSURL class]]) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, value); } else if ([value isKindOfClass:[NSString class]]) { NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet]; NSString *str = [value stringByTrimmingCharactersInSet:set]; if (str.length == 0) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, nil); } else { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, [[NSURL alloc] initWithString:str]); } } } break; case YYEncodingTypeNSArray: case YYEncodingTypeNSMutableArray: { if (meta->_genericCls) { NSArray *valueArr = nil; if ([value isKindOfClass:[NSArray class]]) valueArr = value; else if ([value isKindOfClass:[NSSet class]]) valueArr = ((NSSet *)value).allObjects; if (valueArr) { NSMutableArray *objectArr = [NSMutableArray new]; for (id one in valueArr) { if ([one isKindOfClass:meta->_genericCls]) { [objectArr addObject:one]; } else if ([one isKindOfClass:[NSDictionary class]]) { Class cls = meta->_genericCls; if (meta->_hasCustomClassFromDictionary) { cls = [cls modelCustomClassForDictionary:one]; if (!cls) cls = meta->_genericCls; // for xcode code coverage } NSObject *newOne = [cls new]; [newOne yy_modelSetWithDictionary:one]; if (newOne) [objectArr addObject:newOne]; } } ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, objectArr); } } else { if ([value isKindOfClass:[NSArray class]]) { if (meta->_nsType == YYEncodingTypeNSArray) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, value); } else { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, ((NSArray *)value).mutableCopy); } } else if ([value isKindOfClass:[NSSet class]]) { if (meta->_nsType == YYEncodingTypeNSArray) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, ((NSSet *)value).allObjects); } else { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, ((NSSet *)value).allObjects.mutableCopy); } } } } break; case YYEncodingTypeNSDictionary: case YYEncodingTypeNSMutableDictionary: { if ([value isKindOfClass:[NSDictionary class]]) { if (meta->_genericCls) { NSMutableDictionary *dic = [NSMutableDictionary new]; [((NSDictionary *)value) enumerateKeysAndObjectsUsingBlock:^(NSString *oneKey, id oneValue, BOOL *stop) { if ([oneValue isKindOfClass:[NSDictionary class]]) { Class cls = meta->_genericCls; if (meta->_hasCustomClassFromDictionary) { cls = [cls modelCustomClassForDictionary:oneValue]; if (!cls) cls = meta->_genericCls; // for xcode code coverage } NSObject *newOne = [cls new]; [newOne yy_modelSetWithDictionary:(id)oneValue]; if (newOne) dic[oneKey] = newOne; } }]; ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, dic); } else { if (meta->_nsType == YYEncodingTypeNSDictionary) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, value); } else { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, ((NSDictionary *)value).mutableCopy); } } } } break; case YYEncodingTypeNSSet: case YYEncodingTypeNSMutableSet: { NSSet *valueSet = nil; if ([value isKindOfClass:[NSArray class]]) valueSet = [NSMutableSet setWithArray:value]; else if ([value isKindOfClass:[NSSet class]]) valueSet = ((NSSet *)value); if (meta->_genericCls) { NSMutableSet *set = [NSMutableSet new]; for (id one in valueSet) { if ([one isKindOfClass:meta->_genericCls]) { [set addObject:one]; } else if ([one isKindOfClass:[NSDictionary class]]) { Class cls = meta->_genericCls; if (meta->_hasCustomClassFromDictionary) { cls = [cls modelCustomClassForDictionary:one]; if (!cls) cls = meta->_genericCls; // for xcode code coverage } NSObject *newOne = [cls new]; [newOne yy_modelSetWithDictionary:one]; if (newOne) [set addObject:newOne]; } } ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, set); } else { if (meta->_nsType == YYEncodingTypeNSSet) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, valueSet); } else { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, ((NSSet *)valueSet).mutableCopy); } } } // break; commented for code coverage in next line default: break; } } } else { BOOL isNull = (value == (id)kCFNull); switch (meta->_type & YYEncodingTypeMask) { case YYEncodingTypeObject: { if (isNull) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, (id)nil); } else if ([value isKindOfClass:meta->_cls] || !meta->_cls) { ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, (id)value); } else if ([value isKindOfClass:[NSDictionary class]]) { NSObject *one = nil; if (meta->_getter) { one = ((id (*)(id, SEL))(void *) objc_msgSend)((id)model, meta->_getter); } if (one) { [one yy_modelSetWithDictionary:value]; } else { Class cls = meta->_cls; if (meta->_hasCustomClassFromDictionary) { cls = [cls modelCustomClassForDictionary:value]; if (!cls) cls = meta->_genericCls; // for xcode code coverage } one = [cls new]; [one yy_modelSetWithDictionary:value]; ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)model, meta->_setter, (id)one); } } } break; case YYEncodingTypeClass: { if (isNull) { ((void (*)(id, SEL, Class))(void *) objc_msgSend)((id)model, meta->_setter, (Class)NULL); } else { Class cls = nil; if ([value isKindOfClass:[NSString class]]) { cls = NSClassFromString(value); if (cls) { ((void (*)(id, SEL, Class))(void *) objc_msgSend)((id)model, meta->_setter, (Class)cls); } } else { cls = object_getClass(value); if (cls) { if (class_isMetaClass(cls)) { ((void (*)(id, SEL, Class))(void *) objc_msgSend)((id)model, meta->_setter, (Class)value); } } } } } break; case YYEncodingTypeSEL: { if (isNull) { ((void (*)(id, SEL, SEL))(void *) objc_msgSend)((id)model, meta->_setter, (SEL)NULL); } else if ([value isKindOfClass:[NSString class]]) { SEL sel = NSSelectorFromString(value); if (sel) ((void (*)(id, SEL, SEL))(void *) objc_msgSend)((id)model, meta->_setter, (SEL)sel); } } break; case YYEncodingTypeBlock: { if (isNull) { ((void (*)(id, SEL, void (^)()))(void *) objc_msgSend)((id)model, meta->_setter, (void (^)())NULL); } else if ([value isKindOfClass:YYNSBlockClass()]) { ((void (*)(id, SEL, void (^)()))(void *) objc_msgSend)((id)model, meta->_setter, (void (^)())value); } } break; case YYEncodingTypeStruct: case YYEncodingTypeUnion: case YYEncodingTypeCArray: { if ([value isKindOfClass:[NSValue class]]) { const char *valueType = ((NSValue *)value).objCType; const char *metaType = meta->_info.typeEncoding.UTF8String; if (valueType && metaType && strcmp(valueType, metaType) == 0) { [model setValue:value forKey:meta->_name]; } } } break; case YYEncodingTypePointer: case YYEncodingTypeCString: { if (isNull) { ((void (*)(id, SEL, void *))(void *) objc_msgSend)((id)model, meta->_setter, (void *)NULL); } else if ([value isKindOfClass:[NSValue class]]) { NSValue *nsValue = value; if (nsValue.objCType && strcmp(nsValue.objCType, "^v") == 0) { ((void (*)(id, SEL, void *))(void *) objc_msgSend)((id)model, meta->_setter, nsValue.pointerValue); } } } // break; commented for code coverage in next line default: break; } } } typedef struct { void *modelMeta; ///< _YYModelMeta void *model; ///< id (self) void *dictionary; ///< NSDictionary (json) } ModelSetContext; /** Apply function for dictionary, to set the key-value pair to model. @param _key should not be nil, NSString. @param _value should not be nil. @param _context _context.modelMeta and _context.model should not be nil. */ static void ModelSetWithDictionaryFunction(const void *_key, const void *_value, void *_context) { ModelSetContext *context = _context; __unsafe_unretained _YYModelMeta *meta = (__bridge _YYModelMeta *)(context->modelMeta); __unsafe_unretained _YYModelPropertyMeta *propertyMeta = [meta->_mapper objectForKey:(__bridge id)(_key)]; __unsafe_unretained id model = (__bridge id)(context->model); while (propertyMeta) { if (propertyMeta->_setter) { ModelSetValueForProperty(model, (__bridge __unsafe_unretained id)_value, propertyMeta); } propertyMeta = propertyMeta->_next; }; } /** Apply function for model property meta, to set dictionary to model. @param _propertyMeta should not be nil, _YYModelPropertyMeta. @param _context _context.model and _context.dictionary should not be nil. */ static void ModelSetWithPropertyMetaArrayFunction(const void *_propertyMeta, void *_context) { ModelSetContext *context = _context; __unsafe_unretained NSDictionary *dictionary = (__bridge NSDictionary *)(context->dictionary); __unsafe_unretained _YYModelPropertyMeta *propertyMeta = (__bridge _YYModelPropertyMeta *)(_propertyMeta); if (!propertyMeta->_setter) return; id value = nil; if (propertyMeta->_mappedToKeyArray) { value = YYValueForMultiKeys(dictionary, propertyMeta->_mappedToKeyArray); } else if (propertyMeta->_mappedToKeyPath) { value = YYValueForKeyPath(dictionary, propertyMeta->_mappedToKeyPath); } else { value = [dictionary objectForKey:propertyMeta->_mappedToKey]; } if (value) { __unsafe_unretained id model = (__bridge id)(context->model); ModelSetValueForProperty(model, value, propertyMeta); } } /** Returns a valid JSON object (NSArray/NSDictionary/NSString/NSNumber/NSNull), or nil if an error occurs. @param model Model, can be nil. @return JSON object, nil if an error occurs. */ static id ModelToJSONObjectRecursive(NSObject *model) { if (!model || model == (id)kCFNull) return model; if ([model isKindOfClass:[NSString class]]) return model; if ([model isKindOfClass:[NSNumber class]]) return model; if ([model isKindOfClass:[NSDictionary class]]) { if ([NSJSONSerialization isValidJSONObject:model]) return model; NSMutableDictionary *newDic = [NSMutableDictionary new]; [((NSDictionary *)model) enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) { NSString *stringKey = [key isKindOfClass:[NSString class]] ? key : key.description; if (!stringKey) return; id jsonObj = ModelToJSONObjectRecursive(obj); if (!jsonObj) jsonObj = (id)kCFNull; newDic[stringKey] = jsonObj; }]; return newDic; } if ([model isKindOfClass:[NSSet class]]) { NSArray *array = ((NSSet *)model).allObjects; if ([NSJSONSerialization isValidJSONObject:array]) return array; NSMutableArray *newArray = [NSMutableArray new]; for (id obj in array) { if ([obj isKindOfClass:[NSString class]] || [obj isKindOfClass:[NSNumber class]]) { [newArray addObject:obj]; } else { id jsonObj = ModelToJSONObjectRecursive(obj); if (jsonObj && jsonObj != (id)kCFNull) [newArray addObject:jsonObj]; } } return newArray; } if ([model isKindOfClass:[NSArray class]]) { if ([NSJSONSerialization isValidJSONObject:model]) return model; NSMutableArray *newArray = [NSMutableArray new]; for (id obj in (NSArray *)model) { if ([obj isKindOfClass:[NSString class]] || [obj isKindOfClass:[NSNumber class]]) { [newArray addObject:obj]; } else { id jsonObj = ModelToJSONObjectRecursive(obj); if (jsonObj && jsonObj != (id)kCFNull) [newArray addObject:jsonObj]; } } return newArray; } if ([model isKindOfClass:[NSURL class]]) return ((NSURL *)model).absoluteString; if ([model isKindOfClass:[NSAttributedString class]]) return ((NSAttributedString *)model).string; if ([model isKindOfClass:[NSDate class]]) return [YYISODateFormatter() stringFromDate:(id)model]; if ([model isKindOfClass:[NSData class]]) return nil; _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:[model class]]; if (!modelMeta || modelMeta->_keyMappedCount == 0) return nil; NSMutableDictionary *result = [[NSMutableDictionary alloc] initWithCapacity:64]; __unsafe_unretained NSMutableDictionary *dic = result; // avoid retain and release in block [modelMeta->_mapper enumerateKeysAndObjectsUsingBlock:^(NSString *propertyMappedKey, _YYModelPropertyMeta *propertyMeta, BOOL *stop) { if (!propertyMeta->_getter) return; id value = nil; if (propertyMeta->_isCNumber) { value = ModelCreateNumberFromProperty(model, propertyMeta); } else if (propertyMeta->_nsType) { id v = ((id (*)(id, SEL))(void *) objc_msgSend)((id)model, propertyMeta->_getter); value = ModelToJSONObjectRecursive(v); } else { switch (propertyMeta->_type & YYEncodingTypeMask) { case YYEncodingTypeObject: { id v = ((id (*)(id, SEL))(void *) objc_msgSend)((id)model, propertyMeta->_getter); value = ModelToJSONObjectRecursive(v); if (value == (id)kCFNull) value = nil; } break; case YYEncodingTypeClass: { Class v = ((Class (*)(id, SEL))(void *) objc_msgSend)((id)model, propertyMeta->_getter); value = v ? NSStringFromClass(v) : nil; } break; case YYEncodingTypeSEL: { SEL v = ((SEL (*)(id, SEL))(void *) objc_msgSend)((id)model, propertyMeta->_getter); value = v ? NSStringFromSelector(v) : nil; } break; default: break; } } if (!value) return; if (propertyMeta->_mappedToKeyPath) { NSMutableDictionary *superDic = dic; NSMutableDictionary *subDic = nil; for (NSUInteger i = 0, max = propertyMeta->_mappedToKeyPath.count; i < max; i++) { NSString *key = propertyMeta->_mappedToKeyPath[i]; if (i + 1 == max) { // end if (!superDic[key]) superDic[key] = value; break; } subDic = superDic[key]; if (subDic) { if ([subDic isKindOfClass:[NSDictionary class]]) { subDic = subDic.mutableCopy; superDic[key] = subDic; } else { break; } } else { subDic = [NSMutableDictionary new]; superDic[key] = subDic; } superDic = subDic; subDic = nil; } } else { if (!dic[propertyMeta->_mappedToKey]) { dic[propertyMeta->_mappedToKey] = value; } } }]; if (modelMeta->_hasCustomTransformToDictionary) { BOOL suc = [((id<YYModel>)model) modelCustomTransformToDictionary:dic]; if (!suc) return nil; } return result; } /// Add indent to string (exclude first line) static NSMutableString *ModelDescriptionAddIndent(NSMutableString *desc, NSUInteger indent) { for (NSUInteger i = 0, max = desc.length; i < max; i++) { unichar c = [desc characterAtIndex:i]; if (c == '\n') { for (NSUInteger j = 0; j < indent; j++) { [desc insertString:@" " atIndex:i + 1]; } i += indent * 4; max += indent * 4; } } return desc; } /// Generaate a description string static NSString *ModelDescription(NSObject *model) { static const int kDescMaxLength = 100; if (!model) return @"<nil>"; if (model == (id)kCFNull) return @"<null>"; if (![model isKindOfClass:[NSObject class]]) return [NSString stringWithFormat:@"%@",model]; _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:model.class]; switch (modelMeta->_nsType) { case YYEncodingTypeNSString: case YYEncodingTypeNSMutableString: { return [NSString stringWithFormat:@"\"%@\"",model]; } case YYEncodingTypeNSValue: case YYEncodingTypeNSData: case YYEncodingTypeNSMutableData: { NSString *tmp = model.description; if (tmp.length > kDescMaxLength) { tmp = [tmp substringToIndex:kDescMaxLength]; tmp = [tmp stringByAppendingString:@"..."]; } return tmp; } case YYEncodingTypeNSNumber: case YYEncodingTypeNSDecimalNumber: case YYEncodingTypeNSDate: case YYEncodingTypeNSURL: { return [NSString stringWithFormat:@"%@",model]; } case YYEncodingTypeNSSet: case YYEncodingTypeNSMutableSet: { model = ((NSSet *)model).allObjects; } // no break case YYEncodingTypeNSArray: case YYEncodingTypeNSMutableArray: { NSArray *array = (id)model; NSMutableString *desc = [NSMutableString new]; if (array.count == 0) { return [desc stringByAppendingString:@"[]"]; } else { [desc appendFormat:@"[\n"]; for (NSUInteger i = 0, max = array.count; i < max; i++) { NSObject *obj = array[i]; [desc appendString:@" "]; [desc appendString:ModelDescriptionAddIndent(ModelDescription(obj).mutableCopy, 1)]; [desc appendString:(i + 1 == max) ? @"\n" : @";\n"]; } [desc appendString:@"]"]; return desc; } } case YYEncodingTypeNSDictionary: case YYEncodingTypeNSMutableDictionary: { NSDictionary *dic = (id)model; NSMutableString *desc = [NSMutableString new]; if (dic.count == 0) { return [desc stringByAppendingString:@"{}"]; } else { NSArray *keys = dic.allKeys; [desc appendFormat:@"{\n"]; for (NSUInteger i = 0, max = keys.count; i < max; i++) { NSString *key = keys[i]; NSObject *value = dic[key]; [desc appendString:@" "]; [desc appendFormat:@"%@ = %@",key, ModelDescriptionAddIndent(ModelDescription(value).mutableCopy, 1)]; [desc appendString:(i + 1 == max) ? @"\n" : @";\n"]; } [desc appendString:@"}"]; } return desc; } default: { NSMutableString *desc = [NSMutableString new]; [desc appendFormat:@"<%@: %p>", model.class, model]; if (modelMeta->_allPropertyMetas.count == 0) return desc; // sort property names NSArray *properties = [modelMeta->_allPropertyMetas sortedArrayUsingComparator:^NSComparisonResult(_YYModelPropertyMeta *p1, _YYModelPropertyMeta *p2) { return [p1->_name compare:p2->_name]; }]; [desc appendFormat:@" {\n"]; for (NSUInteger i = 0, max = properties.count; i < max; i++) { _YYModelPropertyMeta *property = properties[i]; NSString *propertyDesc; if (property->_isCNumber) { NSNumber *num = ModelCreateNumberFromProperty(model, property); propertyDesc = num.stringValue; } else { switch (property->_type & YYEncodingTypeMask) { case YYEncodingTypeObject: { id v = ((id (*)(id, SEL))(void *) objc_msgSend)((id)model, property->_getter); propertyDesc = ModelDescription(v); if (!propertyDesc) propertyDesc = @"<nil>"; } break; case YYEncodingTypeClass: { id v = ((id (*)(id, SEL))(void *) objc_msgSend)((id)model, property->_getter); propertyDesc = ((NSObject *)v).description; if (!propertyDesc) propertyDesc = @"<nil>"; } break; case YYEncodingTypeSEL: { SEL sel = ((SEL (*)(id, SEL))(void *) objc_msgSend)((id)model, property->_getter); if (sel) propertyDesc = NSStringFromSelector(sel); else propertyDesc = @"<NULL>"; } break; case YYEncodingTypeBlock: { id block = ((id (*)(id, SEL))(void *) objc_msgSend)((id)model, property->_getter); propertyDesc = block ? ((NSObject *)block).description : @"<nil>"; } break; case YYEncodingTypeCArray: case YYEncodingTypeCString: case YYEncodingTypePointer: { void *pointer = ((void* (*)(id, SEL))(void *) objc_msgSend)((id)model, property->_getter); propertyDesc = [NSString stringWithFormat:@"%p",pointer]; } break; case YYEncodingTypeStruct: case YYEncodingTypeUnion: { NSValue *value = [model valueForKey:property->_name]; propertyDesc = value ? value.description : @"{unknown}"; } break; default: propertyDesc = @"<unknown>"; } } propertyDesc = ModelDescriptionAddIndent(propertyDesc.mutableCopy, 1); [desc appendFormat:@" %@ = %@",property->_name, propertyDesc]; [desc appendString:(i + 1 == max) ? @"\n" : @";\n"]; } [desc appendFormat:@"}"]; return desc; } } } @implementation NSObject (YYModel) + (NSDictionary *)_yy_dictionaryWithJSON:(id)json { if (!json || json == (id)kCFNull) return nil; NSDictionary *dic = nil; NSData *jsonData = nil; if ([json isKindOfClass:[NSDictionary class]]) { dic = json; } else if ([json isKindOfClass:[NSString class]]) { jsonData = [(NSString *)json dataUsingEncoding : NSUTF8StringEncoding]; } else if ([json isKindOfClass:[NSData class]]) { jsonData = json; } if (jsonData) { dic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL]; if (![dic isKindOfClass:[NSDictionary class]]) dic = nil; } return dic; } + (instancetype)yy_modelWithJSON:(id)json { NSDictionary *dic = [self _yy_dictionaryWithJSON:json]; return [self yy_modelWithDictionary:dic]; } + (instancetype)yy_modelWithDictionary:(NSDictionary *)dictionary { if (!dictionary || dictionary == (id)kCFNull) return nil; if (![dictionary isKindOfClass:[NSDictionary class]]) return nil; Class cls = [self class]; _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:cls]; if (modelMeta->_hasCustomClassFromDictionary) { cls = [cls modelCustomClassForDictionary:dictionary] ?: cls; } NSObject *one = [cls new]; if ([one yy_modelSetWithDictionary:dictionary]) return one; return nil; } - (BOOL)yy_modelSetWithJSON:(id)json { NSDictionary *dic = [NSObject _yy_dictionaryWithJSON:json]; return [self yy_modelSetWithDictionary:dic]; } - (BOOL)yy_modelSetWithDictionary:(NSDictionary *)dic { if (!dic || dic == (id)kCFNull) return NO; if (![dic isKindOfClass:[NSDictionary class]]) return NO; _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:object_getClass(self)]; if (modelMeta->_keyMappedCount == 0) return NO; if (modelMeta->_hasCustomWillTransformFromDictionary) { dic = [((id<YYModel>)self) modelCustomWillTransformFromDictionary:dic]; if (![dic isKindOfClass:[NSDictionary class]]) return NO; } ModelSetContext context = {0}; context.modelMeta = (__bridge void *)(modelMeta); context.model = (__bridge void *)(self); context.dictionary = (__bridge void *)(dic); if (modelMeta->_keyMappedCount >= CFDictionaryGetCount((CFDictionaryRef)dic)) { CFDictionaryApplyFunction((CFDictionaryRef)dic, ModelSetWithDictionaryFunction, &context); if (modelMeta->_keyPathPropertyMetas) { CFArrayApplyFunction((CFArrayRef)modelMeta->_keyPathPropertyMetas, CFRangeMake(0, CFArrayGetCount((CFArrayRef)modelMeta->_keyPathPropertyMetas)), ModelSetWithPropertyMetaArrayFunction, &context); } if (modelMeta->_multiKeysPropertyMetas) { CFArrayApplyFunction((CFArrayRef)modelMeta->_multiKeysPropertyMetas, CFRangeMake(0, CFArrayGetCount((CFArrayRef)modelMeta->_multiKeysPropertyMetas)), ModelSetWithPropertyMetaArrayFunction, &context); } } else { CFArrayApplyFunction((CFArrayRef)modelMeta->_allPropertyMetas, CFRangeMake(0, modelMeta->_keyMappedCount), ModelSetWithPropertyMetaArrayFunction, &context); } if (modelMeta->_hasCustomTransformFromDictionary) { return [((id<YYModel>)self) modelCustomTransformFromDictionary:dic]; } return YES; } - (id)yy_modelToJSONObject { /* Apple said: The top level object is an NSArray or NSDictionary. All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull. All dictionary keys are instances of NSString. Numbers are not NaN or infinity. */ id jsonObject = ModelToJSONObjectRecursive(self); if ([jsonObject isKindOfClass:[NSArray class]]) return jsonObject; if ([jsonObject isKindOfClass:[NSDictionary class]]) return jsonObject; return nil; } - (NSData *)yy_modelToJSONData { id jsonObject = [self yy_modelToJSONObject]; if (!jsonObject) return nil; return [NSJSONSerialization dataWithJSONObject:jsonObject options:0 error:NULL]; } - (NSString *)yy_modelToJSONString { NSData *jsonData = [self yy_modelToJSONData]; if (jsonData.length == 0) return nil; return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; } - (id)yy_modelCopy{ if (self == (id)kCFNull) return self; _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:self.class]; if (modelMeta->_nsType) return [self copy]; NSObject *one = [self.class new]; for (_YYModelPropertyMeta *propertyMeta in modelMeta->_allPropertyMetas) { if (!propertyMeta->_getter || !propertyMeta->_setter) continue; if (propertyMeta->_isCNumber) { switch (propertyMeta->_type & YYEncodingTypeMask) { case YYEncodingTypeBool: { bool num = ((bool (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, bool))(void *) objc_msgSend)((id)one, propertyMeta->_setter, num); } break; case YYEncodingTypeInt8: case YYEncodingTypeUInt8: { uint8_t num = ((bool (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, uint8_t))(void *) objc_msgSend)((id)one, propertyMeta->_setter, num); } break; case YYEncodingTypeInt16: case YYEncodingTypeUInt16: { uint16_t num = ((uint16_t (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, uint16_t))(void *) objc_msgSend)((id)one, propertyMeta->_setter, num); } break; case YYEncodingTypeInt32: case YYEncodingTypeUInt32: { uint32_t num = ((uint32_t (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, uint32_t))(void *) objc_msgSend)((id)one, propertyMeta->_setter, num); } break; case YYEncodingTypeInt64: case YYEncodingTypeUInt64: { uint64_t num = ((uint64_t (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, uint64_t))(void *) objc_msgSend)((id)one, propertyMeta->_setter, num); } break; case YYEncodingTypeFloat: { float num = ((float (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, float))(void *) objc_msgSend)((id)one, propertyMeta->_setter, num); } break; case YYEncodingTypeDouble: { double num = ((double (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, double))(void *) objc_msgSend)((id)one, propertyMeta->_setter, num); } break; case YYEncodingTypeLongDouble: { long double num = ((long double (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, long double))(void *) objc_msgSend)((id)one, propertyMeta->_setter, num); } // break; commented for code coverage in next line default: break; } } else { switch (propertyMeta->_type & YYEncodingTypeMask) { case YYEncodingTypeObject: case YYEncodingTypeClass: case YYEncodingTypeBlock: { id value = ((id (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)one, propertyMeta->_setter, value); } break; case YYEncodingTypeSEL: case YYEncodingTypePointer: case YYEncodingTypeCString: { size_t value = ((size_t (*)(id, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_getter); ((void (*)(id, SEL, size_t))(void *) objc_msgSend)((id)one, propertyMeta->_setter, value); } break; case YYEncodingTypeStruct: case YYEncodingTypeUnion: { @try { NSValue *value = [self valueForKey:NSStringFromSelector(propertyMeta->_getter)]; if (value) { [one setValue:value forKey:propertyMeta->_name]; } } @catch (NSException *exception) {} } // break; commented for code coverage in next line default: break; } } } return one; } - (void)yy_modelEncodeWithCoder:(NSCoder *)aCoder { if (!aCoder) return; if (self == (id)kCFNull) { [((id<NSCoding>)self)encodeWithCoder:aCoder]; return; } _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:self.class]; if (modelMeta->_nsType) { [((id<NSCoding>)self)encodeWithCoder:aCoder]; return; } for (_YYModelPropertyMeta *propertyMeta in modelMeta->_allPropertyMetas) { if (!propertyMeta->_getter) return; if (propertyMeta->_isCNumber) { NSNumber *value = ModelCreateNumberFromProperty(self, propertyMeta); if (value) [aCoder encodeObject:value forKey:propertyMeta->_name]; } else { switch (propertyMeta->_type & YYEncodingTypeMask) { case YYEncodingTypeObject: { id value = ((id (*)(id, SEL))(void *)objc_msgSend)((id)self, propertyMeta->_getter); if (value && (propertyMeta->_nsType || [value respondsToSelector:@selector(encodeWithCoder:)])) { if ([value isKindOfClass:[NSValue class]]) { if ([value isKindOfClass:[NSNumber class]]) { [aCoder encodeObject:value forKey:propertyMeta->_name]; } } else { [aCoder encodeObject:value forKey:propertyMeta->_name]; } } } break; case YYEncodingTypeSEL: { SEL value = ((SEL (*)(id, SEL))(void *)objc_msgSend)((id)self, propertyMeta->_getter); if (value) { NSString *str = NSStringFromSelector(value); [aCoder encodeObject:str forKey:propertyMeta->_name]; } } break; case YYEncodingTypeStruct: case YYEncodingTypeUnion: { if (propertyMeta->_isKVCCompatible && propertyMeta->_isStructAvailableForKeyedArchiver) { @try { NSValue *value = [self valueForKey:NSStringFromSelector(propertyMeta->_getter)]; [aCoder encodeObject:value forKey:propertyMeta->_name]; } @catch (NSException *exception) {} } } break; default: break; } } } } - (id)yy_modelInitWithCoder:(NSCoder *)aDecoder { if (!aDecoder) return self; if (self == (id)kCFNull) return self; _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:self.class]; if (modelMeta->_nsType) return self; for (_YYModelPropertyMeta *propertyMeta in modelMeta->_allPropertyMetas) { if (!propertyMeta->_setter) continue; if (propertyMeta->_isCNumber) { NSNumber *value = [aDecoder decodeObjectForKey:propertyMeta->_name]; if ([value isKindOfClass:[NSNumber class]]) { ModelSetNumberToProperty(self, value, propertyMeta); [value class]; } } else { YYEncodingType type = propertyMeta->_type & YYEncodingTypeMask; switch (type) { case YYEncodingTypeObject: { id value = [aDecoder decodeObjectForKey:propertyMeta->_name]; ((void (*)(id, SEL, id))(void *) objc_msgSend)((id)self, propertyMeta->_setter, value); } break; case YYEncodingTypeSEL: { NSString *str = [aDecoder decodeObjectForKey:propertyMeta->_name]; if ([str isKindOfClass:[NSString class]]) { SEL sel = NSSelectorFromString(str); ((void (*)(id, SEL, SEL))(void *) objc_msgSend)((id)self, propertyMeta->_setter, sel); } } break; case YYEncodingTypeStruct: case YYEncodingTypeUnion: { if (propertyMeta->_isKVCCompatible) { @try { NSValue *value = [aDecoder decodeObjectForKey:propertyMeta->_name]; if (value) [self setValue:value forKey:propertyMeta->_name]; } @catch (NSException *exception) {} } } break; default: break; } } } return self; } - (NSUInteger)yy_modelHash { if (self == (id)kCFNull) return [self hash]; _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:self.class]; if (modelMeta->_nsType) return [self hash]; NSUInteger value = 0; NSUInteger count = 0; for (_YYModelPropertyMeta *propertyMeta in modelMeta->_allPropertyMetas) { if (!propertyMeta->_isKVCCompatible) continue; value ^= [[self valueForKey:NSStringFromSelector(propertyMeta->_getter)] hash]; count++; } if (count == 0) value = (long)((__bridge void *)self); return value; } - (BOOL)yy_modelIsEqual:(id)model { if (self == model) return YES; if (![model isMemberOfClass:self.class]) return NO; _YYModelMeta *modelMeta = [_YYModelMeta metaWithClass:self.class]; if (modelMeta->_nsType) return [self isEqual:model]; if ([self hash] != [model hash]) return NO; for (_YYModelPropertyMeta *propertyMeta in modelMeta->_allPropertyMetas) { if (!propertyMeta->_isKVCCompatible) continue; id this = [self valueForKey:NSStringFromSelector(propertyMeta->_getter)]; id that = [model valueForKey:NSStringFromSelector(propertyMeta->_getter)]; if (this == that) continue; if (this == nil || that == nil) return NO; if (![this isEqual:that]) return NO; } return YES; } - (NSString *)yy_modelDescription { return ModelDescription(self); } @end @implementation NSArray (YYModel) + (NSArray *)yy_modelArrayWithClass:(Class)cls json:(id)json { if (!json) return nil; NSArray *arr = nil; NSData *jsonData = nil; if ([json isKindOfClass:[NSArray class]]) { arr = json; } else if ([json isKindOfClass:[NSString class]]) { jsonData = [(NSString *)json dataUsingEncoding : NSUTF8StringEncoding]; } else if ([json isKindOfClass:[NSData class]]) { jsonData = json; } if (jsonData) { arr = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL]; if (![arr isKindOfClass:[NSArray class]]) arr = nil; } return [self yy_modelArrayWithClass:cls array:arr]; } + (NSArray *)yy_modelArrayWithClass:(Class)cls array:(NSArray *)arr { if (!cls || !arr) return nil; NSMutableArray *result = [NSMutableArray new]; for (NSDictionary *dic in arr) { if (![dic isKindOfClass:[NSDictionary class]]) continue; NSObject *obj = [cls yy_modelWithDictionary:dic]; if (obj) [result addObject:obj]; } return result; } @end @implementation NSDictionary (YYModel) + (NSDictionary *)yy_modelDictionaryWithClass:(Class)cls json:(id)json { if (!json) return nil; NSDictionary *dic = nil; NSData *jsonData = nil; if ([json isKindOfClass:[NSDictionary class]]) { dic = json; } else if ([json isKindOfClass:[NSString class]]) { jsonData = [(NSString *)json dataUsingEncoding : NSUTF8StringEncoding]; } else if ([json isKindOfClass:[NSData class]]) { jsonData = json; } if (jsonData) { dic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL]; if (![dic isKindOfClass:[NSDictionary class]]) dic = nil; } return [self yy_modelDictionaryWithClass:cls dictionary:dic]; } + (NSDictionary *)yy_modelDictionaryWithClass:(Class)cls dictionary:(NSDictionary *)dic { if (!cls || !dic) return nil; NSMutableDictionary *result = [NSMutableDictionary new]; for (NSString *key in dic.allKeys) { if (![key isKindOfClass:[NSString class]]) continue; NSObject *obj = [cls yy_modelWithDictionary:dic[key]]; if (obj) result[key] = obj; } return result; } @end ```
/content/code_sandbox/Pods/YYModel/YYModel/NSObject+YYModel.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
17,922
```objective-c // // YFAboutUsViewController.h // BigShow1949 // // Created by on 15-9-4. // #import <UIKit/UIKit.h> @interface YFAuthorViewController : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/YFAuthorViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
49
```objective-c // // YFHomeViewController.m // BigShow1949 // // Created by WangMengqi on 15/9/1. // // #import "YFHomeViewController.h" #import "YFAuthorViewController.h" /******************************************* :, , iPhone5 Github: path_to_url :path_to_url *********************************************/ @implementation YFHomeViewController - (void)viewDidLoad { [super viewDidLoad]; // // // // MVCMTVMVPCBDORM [self setupDataArr:@[@[@"",@"YFButtonViewController"], @[@"",@"YFLabelViewController"], @[@"",@"YFViewLayoutViewController"], @[@"",@"YFViewTransitionViewController"], @[@"",@"YFKnowledgeViewController"], @[@"",@"YFLittleProjectViewController"], @[@"",@"YFAnimationsViewController"], @[@"UIKit",@"YFUIKitViewController"], @[@"app",@"YFImitateAppViewController"], @[@"",@"YFDesignPatternViewController"], @[@"",@"YFToolsViewController"], @[@"",@"YFDataPersistenceViewController"], @[@"",@"YFNetworkRequestViewController"], @[@"/",@"YFBlogViewController"], @[@"",@"YFAlgorithmViewController"], @[@"swift",@"SwiftViewController"],]]; [self setupNav]; } #pragma mark - private - (void)setupNav { self.title = @" "; self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@" " style:UIBarButtonItemStylePlain target:self action:@selector(rightBarClick)]; } - (void)rightBarClick { YFAuthorViewController *aboutUs = [[YFAuthorViewController alloc] init]; [self.navigationController pushViewController:aboutUs animated:YES]; } @end ```
/content/code_sandbox/BigShow1949/Classes/YFHomeViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
363
```objective-c // // YFHomeViewController.h // BigShow1949 // // Created by WangMengqi on 15/9/1. // #import <UIKit/UIKit.h> @interface YFHomeViewController : BaseTableViewController @end ```
/content/code_sandbox/BigShow1949/Classes/YFHomeViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
53
```objective-c // // YFAboutUsViewController.m // BigShow1949 // // Created by on 15-9-4. // #import "YFAuthorViewController.h" @interface YFAuthorViewController () @end @implementation YFAuthorViewController - (void)viewDidLoad { [super viewDidLoad]; self.title = @""; self.view.backgroundColor = [UIColor whiteColor]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; UITextView *aboutUs = [[UITextView alloc] init]; NSString *viewText = @" , , Demo"; aboutUs.editable = NO; aboutUs.backgroundColor = [UIColor lightGrayColor]; aboutUs.frame = CGRectMake(0, 0, 300, 350); aboutUs.center = CGPointMake(YFScreen.width/2, YFScreen.height/2); [self.view addSubview:aboutUs]; // NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.lineSpacing = 10; NSDictionary *attributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:18], NSParagraphStyleAttributeName:paragraphStyle }; aboutUs.attributedText = [[NSAttributedString alloc] initWithString:viewText attributes:attributes]; } @end ```
/content/code_sandbox/BigShow1949/Classes/YFAuthorViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
267
```objective-c // // BaseTableViewController.h // BigShow1949 // // Created by zhht01 on 16/1/13. // #import <UIKit/UIKit.h> @interface BaseTableViewController : UITableViewController - (void)setupDataArr:(NSArray *)dataArr; @end ```
/content/code_sandbox/BigShow1949/Classes/BaseTableViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
61
```objective-c // // BaseTableViewController.m // BigShow1949 // // Created by zhht01 on 16/1/13. // #import "BaseTableViewController.h" #import "RZTransitionsNavigationController.h" // push #import "RZSimpleViewController.h" #import "BigShow-Swift.h" @interface BaseTableViewController () @property (nonatomic, strong) NSArray *titles; @property (nonatomic, strong) NSArray *classNames; @end @implementation BaseTableViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; // UITableViewCellSeparatorStyleNone, // UITableViewCellSeparatorStyleSingleLine, // UITableViewCellSeparatorStyleSingleLineEtched } - (void)setupDataArr:(NSArray *)dataArr { NSMutableArray *tempTitleArr = [NSMutableArray array]; NSMutableArray *tempNamesArr = [NSMutableArray array]; for (NSArray *arr in dataArr) { [tempTitleArr addObject:arr[0]]; [tempNamesArr addObject:arr[1]]; } self.titles = tempTitleArr; self.classNames = tempNamesArr; } #pragma mark - Table view data source - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return self.titles.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *mainCellIdentifier = @"mainCellIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:mainCellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:mainCellIdentifier]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; } cell.selectionStyle = UITableViewCellSelectionStyleGray; NSString *labelText; if (indexPath.row < 9) { labelText = [NSString stringWithFormat:@"0%zd - %@", indexPath.row + 1, self.titles[indexPath.row]]; }else { labelText = [NSString stringWithFormat:@"%zd - %@", indexPath.row + 1, self.titles[indexPath.row]]; } cell.textLabel.text = labelText; cell.detailTextLabel.text = self.classNames[indexPath.row]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; return cell; } #pragma mark - UITableViewDelegate - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 60; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:YES]; NSString *className = self.classNames[indexPath.row]; // : sb, _UIStoryboard NSUInteger classNameLength = className.length; NSUInteger storyBoardLength = @"_UIStoryboard".length; NSUInteger xibLength = @"_xib".length; NSString *suffixClassName; if (classNameLength > storyBoardLength) { suffixClassName = [className substringFromIndex:classNameLength - storyBoardLength]; } // else { // suffixClassName = className; // } if ([suffixClassName isEqualToString:@"_UIStoryboard"]) { className = [className substringToIndex:classNameLength - storyBoardLength]; if ([className isEqualToString:@"RZSimpleViewController"]) { // push RZSimpleViewController *rootViewController = [[RZSimpleViewController alloc] init]; RZTransitionsNavigationController* rootNavController = [[RZTransitionsNavigationController alloc] initWithRootViewController:rootViewController]; [self presentViewController:rootNavController animated:YES completion:nil]; }else { // : storyboard UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:className bundle:nil]; UIViewController *cardVC = [storyBoard instantiateInitialViewController]; if (!cardVC) { cardVC = [storyBoard instantiateViewControllerWithIdentifier:className]; } cardVC.title = self.titles[indexPath.row]; [self.navigationController pushViewController:cardVC animated:YES ]; } }else if ([[className substringFromIndex:classNameLength - xibLength] isEqualToString:@"_xib"]) { className = [className substringToIndex:classNameLength - xibLength]; UIViewController *vc = [[NSClassFromString(className) alloc]initWithNibName:className bundle:nil]; vc.title = self.titles[indexPath.row]; [self.navigationController pushViewController:vc animated:YES]; }else { NSLog(@"className = %@", className); UIViewController *vc = [[NSClassFromString(className) alloc] init]; vc.title = self.titles[indexPath.row]; [self.navigationController pushViewController:vc animated:YES]; } } @end ```
/content/code_sandbox/BigShow1949/Classes/BaseTableViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
959
```objective-c // // YFDataPersistenceViewController.h // BigShow1949 // // Created by zhht01 on 16/4/5. // #import "BaseTableViewController.h" @interface YFDataPersistenceViewController : BaseTableViewController @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/YFDataPersistenceViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
55
```objective-c // // YFDataPersistenceViewController.m // BigShow1949 // // Created by zhht01 on 16/4/5. // #import "YFDataPersistenceViewController.h" @interface YFDataPersistenceViewController () @end @implementation YFDataPersistenceViewController - (void)viewDidLoad { [super viewDidLoad]; [self setupDataArr:@[@[@"JKDBModel()",@"JKDBViewController_UIStoryboard"], @[@"FMDB",@"FMDBBaseUseViewController_UIStoryboard"], @[@"SQLite",@"SQLiteBaseUseViewController_UIStoryboard"], @[@"LCCSqliteManager",@"SheetListController"],]]; } @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/YFDataPersistenceViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
133
```objective-c // // JKDBViewController.m // appStoreDemo // // Created by zhht01 on 16/4/5. // #import "JKDBViewController.h" @interface JKDBViewController () @end @implementation JKDBViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/JKDBViewController/JKDBViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
161
```objective-c // // QueryTableViewController.m // JKDBModel // // Created by zx_04 on 15/7/3. // #import "QueryTableViewController.h" #import "User.h" @interface QueryTableViewController () @property (nonatomic, strong) NSMutableArray *data; @end @implementation QueryTableViewController - (void)viewDidLoad { [super viewDidLoad]; self.tableView.tableFooterView = [UIView new]; if (_type == 4) { UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 40)]; [button setTitle:@"" forState:UIControlStateNormal]; [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal]; [button addTarget:self action:@selector(loadMore) forControlEvents:UIControlEventTouchUpInside]; self.tableView.tableFooterView = button; } _data = [[NSMutableArray alloc] init]; [self loadData]; } - (void)loadData { switch (_type) { case 1: { dispatch_async(dispatch_get_global_queue(0, 0), ^{ NSLog(@""); User *user = [User findFirstByCriteria:@" WHERE age = 20 "]; if (!user) return; [self.data addObject:user]; [self.tableView reloadData]; }); break; } case 2: { dispatch_async(dispatch_get_global_queue(0, 0), ^{ NSLog(@"20"); [self.data addObjectsFromArray:[User findByCriteria:@" WHERE age < 20 "]]; [self.tableView reloadData]; }); break; } case 3: { dispatch_async(dispatch_get_global_queue(0, 0), ^{ NSLog(@""); [self.data addObjectsFromArray:[User findAll]]; [self.tableView reloadData]; }); break; } case 4: { [self loadMore]; } break; default: break; } } - (void)loadMore { static int pk = 5; NSArray *array = [User findByCriteria:[NSString stringWithFormat:@" WHERE pk > %d limit 10",pk]]; pk = ((User *)[array lastObject]).pk; [self.data addObjectsFromArray:array]; [self.tableView reloadData]; } #pragma mark - Table view data source - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.data.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"queryCell"]; UILabel *pkLabel = (UILabel *)[cell viewWithTag:101]; UILabel *nameLabel = (UILabel *)[cell viewWithTag:102]; UILabel *sexLabel = (UILabel *)[cell viewWithTag:103]; UILabel *ageLabel = (UILabel *)[cell viewWithTag:104]; User *user = [self.data objectAtIndex:indexPath.row]; pkLabel.text = [NSString stringWithFormat:@"%d",user.pk]; nameLabel.text = user.name; sexLabel.text = user.sex; ageLabel.text = [NSString stringWithFormat:@"%d",user.age]; return cell; } @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/JKDBViewController/QueryTableViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
653
```objective-c // // QueryTableViewController.h // JKDBModel // // Created by zx_04 on 15/7/3. // #import <UIKit/UIKit.h> @interface QueryTableViewController : UITableViewController @property (nonatomic, assign) int type; @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/JKDBViewController/QueryTableViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
58
```objective-c // // JKDBViewController.h // appStoreDemo // // Created by zhht01 on 16/4/5. // #import <UIKit/UIKit.h> @interface JKDBViewController : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/JKDBViewController/JKDBViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
47
```objective-c // // Depart.h // JKBaseModel // // Created by zx_04 on 15/6/30. // #import "JKDBModel.h" @interface Depart : JKDBModel /** */ @property (nonatomic, copy) NSString *departNum; /** */ @property (nonatomic, copy) NSString *departName; @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/JKDBViewController/Models/Depart.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
78
```objective-c // // Depart.m // JKBaseModel // // Created by zx_04 on 15/6/30. // #import "Depart.h" @implementation Depart @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/JKDBViewController/Models/Depart.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
40
```objective-c // // User.h // JKBaseModel // // Created by zx_04 on 15/6/24. // #import <Foundation/Foundation.h> #import "JKDBModel.h" @interface User : JKDBModel /** */ @property (nonatomic, copy) NSString *account; /** */ @property (nonatomic, copy) NSString *name; /** */ @property (nonatomic, copy) NSString *sex; /** */ @property (nonatomic, copy) NSString *portraitPath; /** */ @property (nonatomic, copy) NSString *moblie; /** */ @property (nonatomic, copy) NSString *descn; /** */ @property (nonatomic, assign) int age; @property (nonatomic, assign) int height; @property (nonatomic, assign) int field1; @property (nonatomic, assign) int field2; @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/JKDBViewController/Models/User.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
194
```objective-c // // User.m // JKBaseModel // // Created by zx_04 on 15/6/24. // #import "User.h" #import "JKDBHelper.h" @interface User () @property (nonatomic, copy) NSString *duty; @end @implementation User #pragma mark - override method +(NSArray *)transients { return [NSArray arrayWithObjects:@"duty",nil]; } @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/JKDBViewController/Models/User.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
89
```objective-c // // JKDataBase.h // JKBaseModel // // Created by zx_04 on 15/6/24. // // #import <Foundation/Foundation.h> #import "FMDB.h" @interface JKDBHelper : NSObject @property (nonatomic, retain, readonly) FMDatabaseQueue *dbQueue; + (JKDBHelper *)shareInstance; + (NSString *)dbPath; @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/JKDBViewController/DBModel/JKDBHelper.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
84
```objective-c // // JKBaseModel.h // JKBaseModel // // Created by zx_04 on 15/6/27. // #import <Foundation/Foundation.h> /** SQLite */ #define SQLTEXT @"TEXT" #define SQLINTEGER @"INTEGER" #define SQLREAL @"REAL" #define SQLBLOB @"BLOB" #define SQLNULL @"NULL" #define PrimaryKey @"primary key" #define primaryId @"pk" @interface JKDBModel : NSObject /** id */ @property (nonatomic, assign) int pk; /** */ @property (retain, readonly, nonatomic) NSMutableArray *columeNames; /** */ @property (retain, readonly, nonatomic) NSMutableArray *columeTypes; /** * */ + (NSDictionary *)getPropertys; /** */ + (NSDictionary *)getAllProperties; /** */ + (BOOL)isExistInTable; /** */ + (NSArray *)getColumns; /** * * */ - (BOOL)saveOrUpdate; /** */ - (BOOL)save; /** */ + (BOOL)saveObjects:(NSArray *)array; /** */ - (BOOL)update; /** */ + (BOOL)updateObjects:(NSArray *)array; /** */ - (BOOL)deleteObject; /** */ + (BOOL)deleteObjects:(NSArray *)array; /** */ + (BOOL)deleteObjectsByCriteria:(NSString *)criteria; /** */ + (BOOL)clearTable; /** */ + (NSArray *)findAll; /** */ + (instancetype)findByPK:(int)inPk; /** */ + (instancetype)findFirstByCriteria:(NSString *)criteria; /** * @" WHERE pk > 5 limit 10" */ + (NSArray *)findByCriteria:(NSString *)criteria; #pragma mark - must be override method /** * * YES */ + (BOOL)createTable; /** property */ + (NSArray *)transients; @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/JKDBViewController/DBModel/JKDBModel.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
405
```objective-c // // JKBaseModel.m // JKBaseModel // // Created by zx_04 on 15/6/27. // #import "JKDBModel.h" #import "JKDBHelper.h" #import <objc/runtime.h> @implementation JKDBModel #pragma mark - override method + (void)initialize { if (self != [JKDBModel self]) { [self createTable]; } } - (instancetype)init { self = [super init]; if (self) { NSDictionary *dic = [self.class getAllProperties]; _columeNames = [[NSMutableArray alloc] initWithArray:[dic objectForKey:@"name"]]; _columeTypes = [[NSMutableArray alloc] initWithArray:[dic objectForKey:@"type"]]; } return self; } #pragma mark - base method /** * */ + (NSDictionary *)getPropertys { NSMutableArray *proNames = [NSMutableArray array]; NSMutableArray *proTypes = [NSMutableArray array]; NSArray *theTransients = [[self class] transients]; unsigned int outCount, i; objc_property_t *properties = class_copyPropertyList([self class], &outCount); for (i = 0; i < outCount; i++) { objc_property_t property = properties[i]; // NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding]; if ([theTransients containsObject:propertyName]) { continue; } [proNames addObject:propertyName]; // NSString *propertyType = [NSString stringWithCString: property_getAttributes(property) encoding:NSUTF8StringEncoding]; /* c char C unsigned char i int I unsigned int l long L unsigned long s short S unsigned short d double D unsigned double f float F unsigned float q long long Q unsigned long long B BOOL @ // NSString @NSString 64long long long Tq SQLite TEXTINTEGERREALBLOBNULL */ if ([propertyType hasPrefix:@"T@"]) { [proTypes addObject:SQLTEXT]; } else if ([propertyType hasPrefix:@"Ti"]||[propertyType hasPrefix:@"TI"]||[propertyType hasPrefix:@"Ts"]||[propertyType hasPrefix:@"TS"]||[propertyType hasPrefix:@"TB"]) { [proTypes addObject:SQLINTEGER]; } else { [proTypes addObject:SQLREAL]; } } free(properties); return [NSDictionary dictionaryWithObjectsAndKeys:proNames,@"name",proTypes,@"type",nil]; } /** pk */ + (NSDictionary *)getAllProperties { NSDictionary *dict = [self.class getPropertys]; NSMutableArray *proNames = [NSMutableArray array]; NSMutableArray *proTypes = [NSMutableArray array]; [proNames addObject:primaryId]; [proTypes addObject:[NSString stringWithFormat:@"%@ %@",SQLINTEGER,PrimaryKey]]; [proNames addObjectsFromArray:[dict objectForKey:@"name"]]; [proTypes addObjectsFromArray:[dict objectForKey:@"type"]]; return [NSDictionary dictionaryWithObjectsAndKeys:proNames,@"name",proTypes,@"type",nil]; } /** */ + (BOOL)isExistInTable { __block BOOL res = NO; JKDBHelper *jkDB = [JKDBHelper shareInstance]; [jkDB.dbQueue inDatabase:^(FMDatabase *db) { NSString *tableName = NSStringFromClass(self.class); res = [db tableExists:tableName]; }]; return res; } + (NSArray *)getColumns { JKDBHelper *jkDB = [JKDBHelper shareInstance]; NSMutableArray *columns = [NSMutableArray array]; [jkDB.dbQueue inDatabase:^(FMDatabase *db) { NSString *tableName = NSStringFromClass(self.class); FMResultSet *resultSet = [db getTableSchema:tableName]; while ([resultSet next]) { NSString *column = [resultSet stringForColumn:@"name"]; [columns addObject:column]; } }]; return [columns copy]; } /** * * YES */ + (BOOL)createTable { FMDatabase *db = [FMDatabase databaseWithPath:[JKDBHelper dbPath]]; if (![db open]) { NSLog(@"!"); return NO; } NSString *tableName = NSStringFromClass(self.class); NSString *columeAndType = [self.class getColumeAndTypeString]; NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(%@);",tableName,columeAndType]; if (![db executeUpdate:sql]) { return NO; } NSMutableArray *columns = [NSMutableArray array]; FMResultSet *resultSet = [db getTableSchema:tableName]; while ([resultSet next]) { NSString *column = [resultSet stringForColumn:@"name"]; [columns addObject:column]; } NSDictionary *dict = [self.class getAllProperties]; NSArray *properties = [dict objectForKey:@"name"]; NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)",columns]; // NSArray *resultArray = [properties filteredArrayUsingPredicate:filterPredicate]; for (NSString *column in resultArray) { NSUInteger index = [properties indexOfObject:column]; NSString *proType = [[dict objectForKey:@"type"] objectAtIndex:index]; NSString *fieldSql = [NSString stringWithFormat:@"%@ %@",column,proType]; NSString *sql = [NSString stringWithFormat:@"ALTER TABLE %@ ADD COLUMN %@ ",NSStringFromClass(self.class),fieldSql]; if (![db executeUpdate:sql]) { return NO; } } [db close]; return YES; } - (BOOL)saveOrUpdate { id primaryValue = [self valueForKey:primaryId]; if ([primaryValue intValue] <= 0) { return [self save]; } return [self update]; } - (BOOL)save { NSString *tableName = NSStringFromClass(self.class); NSMutableString *keyString = [NSMutableString string]; NSMutableString *valueString = [NSMutableString string]; NSMutableArray *insertValues = [NSMutableArray array]; for (int i = 0; i < self.columeNames.count; i++) { NSString *proname = [self.columeNames objectAtIndex:i]; if ([proname isEqualToString:primaryId]) { continue; } [keyString appendFormat:@"%@,", proname]; [valueString appendString:@"?,"]; id value = [self valueForKey:proname]; if (!value) { value = @""; } [insertValues addObject:value]; } [keyString deleteCharactersInRange:NSMakeRange(keyString.length - 1, 1)]; [valueString deleteCharactersInRange:NSMakeRange(valueString.length - 1, 1)]; JKDBHelper *jkDB = [JKDBHelper shareInstance]; __block BOOL res = NO; [jkDB.dbQueue inDatabase:^(FMDatabase *db) { NSString *sql = [NSString stringWithFormat:@"INSERT INTO %@(%@) VALUES (%@);", tableName, keyString, valueString]; res = [db executeUpdate:sql withArgumentsInArray:insertValues]; self.pk = res?[NSNumber numberWithLongLong:db.lastInsertRowId].intValue:0; NSLog(res?@"":@""); }]; return res; } /** */ + (BOOL)saveObjects:(NSArray *)array { //JKBaseModel for (JKDBModel *model in array) { if (![model isKindOfClass:[JKDBModel class]]) { return NO; } } __block BOOL res = YES; JKDBHelper *jkDB = [JKDBHelper shareInstance]; // [jkDB.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) { for (JKDBModel *model in array) { NSString *tableName = NSStringFromClass(model.class); NSMutableString *keyString = [NSMutableString string]; NSMutableString *valueString = [NSMutableString string]; NSMutableArray *insertValues = [NSMutableArray array]; for (int i = 0; i < model.columeNames.count; i++) { NSString *proname = [model.columeNames objectAtIndex:i]; if ([proname isEqualToString:primaryId]) { continue; } [keyString appendFormat:@"%@,", proname]; [valueString appendString:@"?,"]; id value = [model valueForKey:proname]; if (!value) { value = @""; } [insertValues addObject:value]; } [keyString deleteCharactersInRange:NSMakeRange(keyString.length - 1, 1)]; [valueString deleteCharactersInRange:NSMakeRange(valueString.length - 1, 1)]; NSString *sql = [NSString stringWithFormat:@"INSERT INTO %@(%@) VALUES (%@);", tableName, keyString, valueString]; BOOL flag = [db executeUpdate:sql withArgumentsInArray:insertValues]; model.pk = flag?[NSNumber numberWithLongLong:db.lastInsertRowId].intValue:0; NSLog(flag?@"":@""); if (!flag) { res = NO; *rollback = YES; return; } } }]; return res; } /** */ - (BOOL)update { JKDBHelper *jkDB = [JKDBHelper shareInstance]; __block BOOL res = NO; [jkDB.dbQueue inDatabase:^(FMDatabase *db) { NSString *tableName = NSStringFromClass(self.class); id primaryValue = [self valueForKey:primaryId]; if (!primaryValue || primaryValue <= 0) { return ; } NSMutableString *keyString = [NSMutableString string]; NSMutableArray *updateValues = [NSMutableArray array]; for (int i = 0; i < self.columeNames.count; i++) { NSString *proname = [self.columeNames objectAtIndex:i]; if ([proname isEqualToString:primaryId]) { continue; } [keyString appendFormat:@" %@=?,", proname]; id value = [self valueForKey:proname]; if (!value) { value = @""; } [updateValues addObject:value]; } // [keyString deleteCharactersInRange:NSMakeRange(keyString.length - 1, 1)]; NSString *sql = [NSString stringWithFormat:@"UPDATE %@ SET %@ WHERE %@ = ?;", tableName, keyString, primaryId]; [updateValues addObject:primaryValue]; res = [db executeUpdate:sql withArgumentsInArray:updateValues]; NSLog(res?@"":@""); }]; return res; } /** */ + (BOOL)updateObjects:(NSArray *)array { for (JKDBModel *model in array) { if (![model isKindOfClass:[JKDBModel class]]) { return NO; } } __block BOOL res = YES; JKDBHelper *jkDB = [JKDBHelper shareInstance]; // [jkDB.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) { for (JKDBModel *model in array) { NSString *tableName = NSStringFromClass(model.class); id primaryValue = [model valueForKey:primaryId]; if (!primaryValue || primaryValue <= 0) { res = NO; *rollback = YES; return; } NSMutableString *keyString = [NSMutableString string]; NSMutableArray *updateValues = [NSMutableArray array]; for (int i = 0; i < model.columeNames.count; i++) { NSString *proname = [model.columeNames objectAtIndex:i]; if ([proname isEqualToString:primaryId]) { continue; } [keyString appendFormat:@" %@=?,", proname]; id value = [model valueForKey:proname]; if (!value) { value = @""; } [updateValues addObject:value]; } // [keyString deleteCharactersInRange:NSMakeRange(keyString.length - 1, 1)]; NSString *sql = [NSString stringWithFormat:@"UPDATE %@ SET %@ WHERE %@=?;", tableName, keyString, primaryId]; [updateValues addObject:primaryValue]; BOOL flag = [db executeUpdate:sql withArgumentsInArray:updateValues]; NSLog(flag?@"":@""); if (!flag) { res = NO; *rollback = YES; return; } } }]; return res; } /** */ - (BOOL)deleteObject { JKDBHelper *jkDB = [JKDBHelper shareInstance]; __block BOOL res = NO; [jkDB.dbQueue inDatabase:^(FMDatabase *db) { NSString *tableName = NSStringFromClass(self.class); id primaryValue = [self valueForKey:primaryId]; if (!primaryValue || primaryValue <= 0) { return ; } NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@ = ?",tableName,primaryId]; res = [db executeUpdate:sql withArgumentsInArray:@[primaryValue]]; NSLog(res?@"":@""); }]; return res; } /** */ + (BOOL)deleteObjects:(NSArray *)array { for (JKDBModel *model in array) { if (![model isKindOfClass:[JKDBModel class]]) { return NO; } } __block BOOL res = YES; JKDBHelper *jkDB = [JKDBHelper shareInstance]; // [jkDB.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) { for (JKDBModel *model in array) { NSString *tableName = NSStringFromClass(model.class); id primaryValue = [model valueForKey:primaryId]; if (!primaryValue || primaryValue <= 0) { return ; } NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@ = ?",tableName,primaryId]; BOOL flag = [db executeUpdate:sql withArgumentsInArray:@[primaryValue]]; NSLog(flag?@"":@""); if (!flag) { res = NO; *rollback = YES; return; } } }]; return res; } /** */ + (BOOL)deleteObjectsByCriteria:(NSString *)criteria { JKDBHelper *jkDB = [JKDBHelper shareInstance]; __block BOOL res = NO; [jkDB.dbQueue inDatabase:^(FMDatabase *db) { NSString *tableName = NSStringFromClass(self.class); NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ %@ ",tableName,criteria]; res = [db executeUpdate:sql]; NSLog(res?@"":@""); }]; return res; } /** */ + (BOOL)clearTable { JKDBHelper *jkDB = [JKDBHelper shareInstance]; __block BOOL res = NO; [jkDB.dbQueue inDatabase:^(FMDatabase *db) { NSString *tableName = NSStringFromClass(self.class); NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@",tableName]; res = [db executeUpdate:sql]; NSLog(res?@"":@""); }]; return res; } /** */ + (NSArray *)findAll { NSLog(@"jkdb---%s",__func__); JKDBHelper *jkDB = [JKDBHelper shareInstance]; NSMutableArray *users = [NSMutableArray array]; [jkDB.dbQueue inDatabase:^(FMDatabase *db) { NSString *tableName = NSStringFromClass(self.class); NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@",tableName]; FMResultSet *resultSet = [db executeQuery:sql]; while ([resultSet next]) { JKDBModel *model = [[self.class alloc] init]; for (int i=0; i< model.columeNames.count; i++) { NSString *columeName = [model.columeNames objectAtIndex:i]; NSString *columeType = [model.columeTypes objectAtIndex:i]; if ([columeType isEqualToString:SQLTEXT]) { [model setValue:[resultSet stringForColumn:columeName] forKey:columeName]; } else { [model setValue:[NSNumber numberWithLongLong:[resultSet longLongIntForColumn:columeName]] forKey:columeName]; } } [users addObject:model]; FMDBRelease(model); } }]; return users; } /** */ + (instancetype)findFirstByCriteria:(NSString *)criteria { NSArray *results = [self.class findByCriteria:criteria]; if (results.count < 1) { return nil; } return [results firstObject]; } + (instancetype)findByPK:(int)inPk { NSString *condition = [NSString stringWithFormat:@"WHERE %@=%d",primaryId,inPk]; return [self findFirstByCriteria:condition]; } /** */ + (NSArray *)findByCriteria:(NSString *)criteria { JKDBHelper *jkDB = [JKDBHelper shareInstance]; NSMutableArray *users = [NSMutableArray array]; [jkDB.dbQueue inDatabase:^(FMDatabase *db) { NSString *tableName = NSStringFromClass(self.class); NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ %@",tableName,criteria]; FMResultSet *resultSet = [db executeQuery:sql]; while ([resultSet next]) { JKDBModel *model = [[self.class alloc] init]; for (int i=0; i< model.columeNames.count; i++) { NSString *columeName = [model.columeNames objectAtIndex:i]; NSString *columeType = [model.columeTypes objectAtIndex:i]; if ([columeType isEqualToString:SQLTEXT]) { [model setValue:[resultSet stringForColumn:columeName] forKey:columeName]; } else { [model setValue:[NSNumber numberWithLongLong:[resultSet longLongIntForColumn:columeName]] forKey:columeName]; } } [users addObject:model]; FMDBRelease(model); } }]; return users; } #pragma mark - util method + (NSString *)getColumeAndTypeString { NSMutableString* pars = [NSMutableString string]; NSDictionary *dict = [self.class getAllProperties]; NSMutableArray *proNames = [dict objectForKey:@"name"]; NSMutableArray *proTypes = [dict objectForKey:@"type"]; for (int i=0; i< proNames.count; i++) { [pars appendFormat:@"%@ %@",[proNames objectAtIndex:i],[proTypes objectAtIndex:i]]; if(i+1 != proNames.count) { [pars appendString:@","]; } } return pars; } - (NSString *)description { NSString *result = @""; NSDictionary *dict = [self.class getAllProperties]; NSMutableArray *proNames = [dict objectForKey:@"name"]; for (int i = 0; i < proNames.count; i++) { NSString *proName = [proNames objectAtIndex:i]; id proValue = [self valueForKey:proName]; result = [result stringByAppendingFormat:@"%@:%@\n",proName,proValue]; } return result; } #pragma mark - must be override method /** property */ + (NSArray *)transients { return [NSArray array]; } @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/JKDBViewController/DBModel/JKDBModel.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
4,061
```objective-c // // JKDataBase.m // JKBaseModel // // Created by zx_04 on 15/6/24. // // #import "JKDBHelper.h" @interface JKDBHelper () @property (nonatomic, retain) FMDatabaseQueue *dbQueue; @end @implementation JKDBHelper static JKDBHelper *_instance = nil; + (instancetype)shareInstance { static dispatch_once_t onceToken ; dispatch_once(&onceToken, ^{ _instance = [[super allocWithZone:NULL] init] ; }) ; return _instance; } + (NSString *)dbPath { NSString *docsdir = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSFileManager *filemanage = [NSFileManager defaultManager]; docsdir = [docsdir stringByAppendingPathComponent:@"JKBD"]; BOOL isDir; BOOL exit =[filemanage fileExistsAtPath:docsdir isDirectory:&isDir]; if (!exit || !isDir) { [filemanage createDirectoryAtPath:docsdir withIntermediateDirectories:YES attributes:nil error:nil]; } NSString *dbpath = [docsdir stringByAppendingPathComponent:@"jkdb.sqlite"]; return dbpath; } - (FMDatabaseQueue *)dbQueue { if (_dbQueue == nil) { _dbQueue = [[FMDatabaseQueue alloc] initWithPath:[self.class dbPath]]; } return _dbQueue; } + (id)allocWithZone:(struct _NSZone *)zone { return [JKDBHelper shareInstance]; } - (id)copyWithZone:(struct _NSZone *)zone { return [JKDBHelper shareInstance]; } #if ! __has_feature(objc_arc) - (oneway void)release { } - (id)autorelease { return _instance; } - (NSUInteger)retainCount { return 1; } #endif @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/JKDBViewController/DBModel/JKDBHelper.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
410
```objective-c // // SQLiteBaseUseViewController.h // BigShow1949 // // Created by zhht01 on 16/4/18. // #import <UIKit/UIKit.h> @interface SQLiteBaseUseViewController : UIViewController - (IBAction)insert; - (IBAction)delete_; - (IBAction)update; - (IBAction)select; @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/SQLite基本使用/SQLiteBaseUseViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
74
```objective-c // // SQLiteBaseUseViewController.m // BigShow1949 // // Created by zhht01 on 16/4/18. // #import "SQLiteBaseUseViewController.h" #import <sqlite3.h> @interface SQLiteBaseUseViewController () { sqlite3 *_db; } @end @implementation SQLiteBaseUseViewController - (void)viewDidLoad { [super viewDidLoad]; // db,, , // NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *fileName = [doc stringByAppendingPathComponent:@"students.sqlite"]; NSLog(@"fileName = %@", fileName); // OCC const char *cfileName = fileName.UTF8String; int result = sqlite3_open(cfileName, &_db); if (result==SQLITE_OK) { // NSLog(@""); //2. const char *sql="CREATE TABLE IF NOT EXISTS t_students (id integer PRIMARY KEY AUTOINCREMENT,name text NOT NULL,age integer NOT NULL);"; char *errmsg=NULL; result = sqlite3_exec(_db, sql, NULL, NULL, &errmsg); if (result==SQLITE_OK) { NSLog(@""); NSString *insertSql=[NSString stringWithFormat:@"INSERT INTO t_students (name,age) VALUES ('', 22);"]; //2.SQL char *errmsg=NULL; int result = sqlite3_exec(_db, insertSql.UTF8String, NULL, NULL, &errmsg); if (result == SQLITE_OK) { NSLog(@"--%s", errmsg); }else { NSLog(@"--%s",errmsg); } }else { NSLog(@"----%s",errmsg); } }else { NSLog(@""); } } - (IBAction)insert { sqlite3 *db; for (int i=0; i<20; i++) { //1.SQL NSString *name=[NSString stringWithFormat:@"--%d",arc4random_uniform(100)]; int age=arc4random_uniform(20)+10; // NSString *sql=[NSString stringWithFormat:@"INSERT INTO t_students (name,age) VALUES ('%@',%d);",name,age]; // NSString *sql=[NSString stringWithFormat:@"INSERT INTO t_students (name,age) VALUES ('', 22);"]; // // //2.SQL // char *errmsg=NULL; // int result = sqlite3_exec(db, sql.UTF8String, NULL, NULL, &errmsg); // NSLog(@"result = %zd", result); // if (errmsg) {// // NSLog(@"--%s",errmsg); // }else{ // NSLog(@"--%s", errmsg); // } NSString *insertSql=[NSString stringWithFormat:@"INSERT INTO t_students (name,age) VALUES ('2we', 22);"]; //2.SQL char *errmsg=NULL; int result = sqlite3_exec(db, insertSql.UTF8String, NULL, NULL, &errmsg); NSLog(@"result = %d", result); if (result == SQLITE_OK) { NSLog(@"--%s", errmsg); }else { NSLog(@"--%s",errmsg); } } } - (IBAction)delete_ { } - (IBAction)update { } - (IBAction)select { const char *sql="SELECT id,name,age FROM t_students WHERE age<20;"; sqlite3_stmt *stmt=NULL; /* sqlsql-1sqlNULL */ // int result = sqlite3_prepare_v2(_db, sql, -1, &stmt, NULL); if (result == SQLITE_OK) {//SQL NSLog(@""); //sqlite3_stepstmt while (sqlite3_step(stmt)==SQLITE_ROW) {// // //(1)0int int ID=sqlite3_column_int(stmt, 0); //(2)1text const unsigned char *name=sqlite3_column_text(stmt, 1); //(3)2int int age=sqlite3_column_int(stmt, 2); // NSLog(@"%d %s %d",ID,name,age); printf("%d %s %d\n",ID,name,age); } }else { NSLog(@""); } } @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/SQLite基本使用/SQLiteBaseUseViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
932
```objective-c // // W3CViewController.h // BigShow1949 // // Created by zhht01 on 16/4/18. // #import <UIKit/UIKit.h> @interface W3CViewController : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/W3C/W3CViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
50
```objective-c // // W3CViewController.m // BigShow1949 // // Created by zhht01 on 16/4/18. // #import "W3CViewController.h" @interface W3CViewController () @end @implementation W3CViewController - (void)viewDidLoad { [super viewDidLoad]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* SELECT : eg:SELECT City,Address FROM t_person; DISTINCT:distinct eg:SELECT DISTINCT City FROM t_person; WHERE: eg:SELECT * FROM t_person WHERE City = 'Beijing'; AND&OR: WHERE eg:SELECT * FROM t_person WHERE FirstName = 'Fan' OR LastName = 'Adams'; ORDER BY: eg:SELECT LastName,Year FROM t_person ORDER BY Year DESC; INSERT INTO: eg:INSERT INTO t_person (Address,Year,City,LastName) VALUES ('Changan Street',1989,'Beijing','Carter'); UPDATE: eg:UPDATE t_person SET LirstName = 'Fant' WHERE LastName = 'White'; DELETE: eg:DELETE FROM t_person WHERE lastName = 'Carter'; : DELETE FROM ; TOP(LIMIT): eg:SELECT * SELECT TOP 2 * FROM t_person; : SELECT * FROM t_person LIMIT 2; LIKE: WHERE eg:SELECT * FROM t_person WHERE City LIKE'N%'; IN: WHERE eg:SELECT * FROM t_person WHERE LastName IN ('Adams','Carter'); BETWEEN ... AND: eg:SELECT * FROM t_person WHERE LastName BETWEEN 'Adams' AND 'Carter'; DROP:; eg:DROP TABLE t_person; ALTER: eg:ALTER TABLE t_parking ADD cost date; : ALTER TABLE t_parking DROP cost date; : 1. create table _temp as select _id,name,age,balance from person; select * from _temp; 2. drop table person; 3. alter table _temp rename to person; */ @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/W3C/W3CViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
434
```objective-c // // SheetInsertView.m // DatabaseMangerDemo // // Created by LccLcc on 15/12/9. // #import "Define.h" #import "SheetInsertView.h" #import "LccCell.h" #import "LCCSqliteManager.h" @implementation SheetInsertView { // NSMutableArray *_attributes; // UITextField *_titleTextFiled; //manager LCCSqliteManager *_manager; } - (instancetype)initWithFrame:(CGRect)frame{ if (self = [super initWithFrame:frame]) { // UIView * blackgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KWidth, KHeight)]; [self addSubview:blackgroundView]; blackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:.5]; // self.tableView = [[UITableView alloc]initWithFrame:CGRectMake((KWidth - 300)/2, 70, 300, KHeight - 250)]; if (iPhone4) { self.tableView.frame = CGRectMake((KWidth - 300)/2, 20, 300, KHeight - 250); } [blackgroundView addSubview:self.tableView ]; self.tableView.backgroundColor = [UIColor clearColor]; self.tableView.delegate = self; self.tableView.dataSource = self; self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; // UIView * backGroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 180, 40)]; _titleTextFiled = [[UITextField alloc]initWithFrame:CGRectMake(60 , 0, 180 , 40)]; _titleTextFiled.borderStyle = UITextBorderStyleRoundedRect; [backGroundView addSubview:_titleTextFiled]; _titleTextFiled.placeholder = @""; _titleTextFiled.backgroundColor = [UIColor colorWithWhite:.95 alpha:1]; self.tableView.tableHeaderView=backGroundView; // UIButton *ensureButton = [[UIButton alloc]initWithFrame:CGRectMake(10, 70, 40, 40)]; if (iPhone4) { ensureButton.frame = CGRectMake(10, 30, 40, 40); } [blackgroundView addSubview:ensureButton]; [ensureButton setImage:[UIImage imageNamed:@"btn_save"] forState:UIControlStateNormal]; [ensureButton addTarget:self action:@selector(_insertSheetActon) forControlEvents:UIControlEventTouchUpInside]; // UIButton *deleateButton = [[UIButton alloc]initWithFrame:CGRectMake(KWidth - 50, 70, 40, 40)]; if (iPhone4) { deleateButton.frame = CGRectMake(KWidth - 50, 30, 40, 40); } [blackgroundView addSubview:deleateButton]; [deleateButton setImage:[UIImage imageNamed:@"btn_cannel"] forState:UIControlStateNormal]; [deleateButton addTarget:self action:@selector(_deleateAction) forControlEvents:UIControlEventTouchUpInside]; _manager = [LCCSqliteManager shareInstance]; } return self; } #pragma mark - Action - (void)_insertSheetActon{ _attributes = [[NSMutableArray alloc]init]; _sheetTitle = _titleTextFiled.text; [self endEditing:YES]; if ([_sheetTitle isEqual: @""]) { [self.delegate insertError]; return; } NSLog(@"self.cellCount = %ld",(long)self.cellCount); for (int i = 0; i < self.cellCount; i ++) { NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:0]; LccCell *pCell = [self.tableView cellForRowAtIndexPath:path ]; NSLog(@"pcell = %@",pCell); if (pCell != nil&&[pCell.textFiled.text isEqualToString:@""]) { [self.delegate insertError]; return; } [_attributes addObject:pCell.textFiled.text]; } // // BOOL result = [_manager createSheetWithName:_sheetTitle attributes:_attributes primaryKey:nil]; BOOL result = [_manager createSheetWithSheetHandler:^(LCCSqliteSheetHandler *sheet) { sheet.sheetName = _sheetTitle; sheet.sheetField = _attributes; }]; if (result == YES) { [self _clear]; [self.delegate insertSuccess]; } if (result == NO) { [self.delegate insertError]; } } - (void)_deleateAction{ [self.delegate closeInsertlView]; } - (void)_clear{ [self endEditing:YES]; _titleTextFiled.text = @""; for (int i = 0; i < self.cellCount; i ++) { NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:0]; LccCell *pCell = [self.tableView cellForRowAtIndexPath:path ]; pCell.textFiled.text = @""; } } #pragma mark - TableViewDelegate //- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // // return 1; //} - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ return 40; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.cellCount; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { LccCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sheetCell"]; if (cell == nil) { cell = [[LccCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"sheetCell" andWidth:300]; } // cell.tag = indexPath.row; cell.selectionStyle = UITableViewCellSelectionStyleNone; cell.textFiled.placeholder = [NSString stringWithFormat:@"%ld:",(long)indexPath.row]; cell.backgroundColor = [UIColor clearColor]; return cell; } @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/W3C/LCCSqliteManager/UI/SheetList/SheetInsertView.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,208
```objective-c // // SheetListController.m // DatabaseMangerDemo // // Created by LccLcc on 15/11/27. // #import "Define.h" #import "SheetListController.h" #import "LCCSqliteManager.h" #import "DataListController.h" #import "LccButton.h" #import "SheetInsertView.h" @interface SheetListController ()<UITableViewDelegate,UITableViewDataSource,SheetInsertViewDelegate> { // NSInteger _attributesCount; // UIAlertAction *_nextAction; // LCCSqliteManager *_manager; // SheetInsertView *_sheetInsertView; } @end @implementation SheetListController - (void)viewDidLoad { [super viewDidLoad]; [self _createButtonItem]; // _manager = [LCCSqliteManager shareInstance]; [_manager openSqliteFile:@"database"]; // [_manager createSheetWithSheetHandler:^(LCCSqliteSheetHandler *sheet) { sheet.sheetName = @""; sheet.sheetType = LCCSheetTypeVariable; sheet.sheetField = @[@"",@"",@"",@""]; sheet.primaryKey = @[@"",@""]; }]; [_manager createSheetWithSheetHandler:^(LCCSqliteSheetHandler *sheet) { sheet.sheetName = @""; sheet.sheetType = LCCSheetTypeVariable; sheet.sheetField = @[@"",@"",@"",@"",@"",@""]; sheet.forgienKey = @[@"",@""]; sheet.referencesSheetName = @""; sheet.referenceskey = @[@"",@""]; sheet.updateReferencesType = LCCSqliteReferencesKeyTypeCasCade; sheet.deleateReferencesType = LCCSqliteReferencesKeyTypeCasCade; }]; // _sheetListArray = [_manager getAllSheetNames]; // self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain]; [self.view addSubview:self.tableView]; self.tableView.delegate = self; self.tableView.dataSource = self; } #pragma mark - - (void)_createButtonItem{ LccButton * createButton = [LccButton buttonWithType:UIButtonTypeSystem]; [createButton setTitle:@"" forState:UIControlStateNormal]; [createButton addTarget:self action:@selector(_addSheetAction:) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *createButtonItem = [[UIBarButtonItem alloc]initWithCustomView:createButton]; [self.navigationItem setRightBarButtonItem: createButtonItem]; } #pragma mark - Action - (void)_addSheetAction:(id)sender { UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleAlert]; [alter addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) { textField.placeholder = @"15"; [textField addTarget:self action:@selector(_inputChangeAction:) forControlEvents:UIControlEventEditingChanged]; }]; _nextAction = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { _sheetInsertView = [[SheetInsertView alloc]initWithFrame:CGRectMake(0, -KHeight, KWidth, KHeight) ]; _sheetInsertView.cellCount = _attributesCount; _sheetInsertView.delegate = self; [self.navigationController.view addSubview:_sheetInsertView]; [self.navigationController.view bringSubviewToFront:_sheetInsertView]; [UIView animateWithDuration:.3 animations:^{ _sheetInsertView.frame = CGRectMake(0, 0, KWidth, KHeight); } completion:nil]; }]; _nextAction.enabled = NO; UIAlertAction *cannleAction = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleDefault handler:nil]; [alter addAction:_nextAction]; [alter addAction:cannleAction]; [self presentViewController:alter animated:YES completion:nil]; } - (void)_inputChangeAction:(UITextField *)pTextFiled{ _nextAction.enabled = NO; NSLog(@"%@",pTextFiled.text); if ([pTextFiled.text integerValue] >= 1 && [pTextFiled.text integerValue] <=5) { _nextAction.enabled = YES; _attributesCount = [pTextFiled.text integerValue]; } } #pragma mark - TableViewDataSource - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.sheetListArray.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"sheetCell"]; if (cell == nil) { cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"sheetCell"]; } cell.textLabel.text = _sheetListArray[indexPath.row]; return cell; } #pragma mark - TableViewDelegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ // UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]]; // DataListController *dataViewController = (DataListController*)[storyboard instantiateViewControllerWithIdentifier:@"DataList" ]; DataListController *dataViewController = [[DataListController alloc] init]; dataViewController.sheetTitle = _sheetListArray[indexPath.row]; [self.navigationController pushViewController:dataViewController animated:YES]; //tintcolor(Back) self.navigationController.navigationBar.tintColor = [UIColor grayColor]; } - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; // [_manager deleateSheetWithName:cell.textLabel.text]; // _sheetListArray = [_manager getAllSheetNames]; NSLog(@",: %@",_sheetListArray); [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { } } #pragma mark - SheetInsertViewDelegate // - (void)closeInsertlView{ [_sheetInsertView endEditing:YES]; [UIView animateWithDuration:.2 animations:^{ _sheetInsertView.frame = CGRectMake(0, -KHeight, KWidth, KHeight); } completion:nil]; } // -(void)insertSuccess{ // _sheetListArray = [_manager getAllSheetNames]; [self.tableView reloadData]; UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *cannleAction = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleDefault handler:nil]; [alter addAction:cannleAction]; [self presentViewController:alter animated:YES completion:nil]; } -(void)insertError{ UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *cannleAction = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleDefault handler:nil]; [alter addAction:cannleAction]; [self presentViewController:alter animated:YES completion:nil]; } @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/W3C/LCCSqliteManager/UI/SheetList/SheetListController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,463
```objective-c // // LccButton.m // DatabaseMangerDemo // // Created by LccLcc on 15/12/2. // #import "LccButton.h" @implementation LccButton +(instancetype)buttonWithType:(UIButtonType)type{ LccButton * btn = [super buttonWithType:type]; btn.backgroundColor = [UIColor clearColor]; btn.frame = CGRectMake(0, 0, 45, 25); // btn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 40); [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal]; btn.titleLabel.font = [UIFont systemFontOfSize:14]; btn.layer.cornerRadius = 4; btn.layer.borderWidth = 1; btn.layer.borderColor = [UIColor grayColor].CGColor; return btn; } @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/W3C/LCCSqliteManager/UI/SheetList/LccButton.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
175
```objective-c // // SheetInsertView.h // DatabaseMangerDemo // // Created by LccLcc on 15/12/9. // #import "DataInsertView.h" @protocol SheetInsertViewDelegate <NSObject> // - (void)insertError; // - (void)insertSuccess; // - (void)closeInsertlView; @end @interface SheetInsertView : UIView<UITableViewDelegate,UITableViewDataSource> //cell @property(nonatomic,assign)NSInteger cellCount; // @property(nonatomic,strong)NSString *sheetTitle; @property(nonatomic,weak)id<SheetInsertViewDelegate>delegate; @property(nonatomic,strong)UITableView *tableView; @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/W3C/LCCSqliteManager/UI/SheetList/SheetInsertView.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
135
```objective-c // // LccButton.h // DatabaseMangerDemo // // Created by LccLcc on 15/12/2. // #import <UIKit/UIKit.h> @interface LccButton : UIButton @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/W3C/LCCSqliteManager/UI/SheetList/LccButton.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
49
```objective-c // // LccCell.h // DatabaseMangerDemo // // Created by LccLcc on 15/12/1. // #import <UIKit/UIKit.h> @interface LccCell : UITableViewCell @property(nonatomic,strong)UITextField *textFiled; - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier andWidth:(CGFloat)width; @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/W3C/LCCSqliteManager/UI/DataList/LccCell.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
81
```objective-c // // DataEditView.h // BigShow1949 // // Created by zhht01 on 16/4/22. // #import <UIKit/UIKit.h> @protocol DataEditViewDelegate <NSObject> // - (void)ensureAction:(NSArray *)dataArray; // - (void)closeAction; @end @interface DataEditView : UIView<UITableViewDelegate,UITableViewDataSource> @property(nonatomic,weak)id<DataEditViewDelegate>delegate; @property(nonatomic,strong)UITableView *tableView; @property (nonatomic, strong) NSArray *placeholders; // cell placeholder() @property (nonatomic, strong) NSArray *texts; // cell text() @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/W3C/LCCSqliteManager/UI/DataList/DataEditView.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
134
```objective-c // // SheetListController.h // DatabaseMangerDemo // // Created by LccLcc on 15/11/27. // #import <UIKit/UIKit.h> @interface SheetListController : UIViewController // @property(nonatomic,strong)NSArray *sheetListArray; // @property(nonatomic,strong)UITableView *tableView; @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/W3C/LCCSqliteManager/UI/SheetList/SheetListController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
70
```objective-c // // DataUpdateView.h // DatabaseMangerDemo // // Created by LccLcc on 15/12/11. // #import "DataInsertView.h" @protocol DataUpdateViewDelegate <NSObject> // - (void)updateError; // - (void)updateSuccess; // - (void)closeUpdateView; @end @interface DataUpdateView : UIView @property(nonatomic,strong)NSString *sheetTitle; @property(nonatomic,weak)id<DataUpdateViewDelegate>delegate; // @property(nonatomic,strong)NSString *updateCondition; // condition // @property (nonatomic, strong) NSArray *updateArray; @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/W3C/LCCSqliteManager/UI/DataList/DataUpdateView.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
133
```objective-c // // LccCell.m // DatabaseMangerDemo // // Created by LccLcc on 15/12/1. // #import "Define.h" #import "LccCell.h" @implementation LccCell - (void)awakeFromNib { // Initialization code } - (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; // Configure the view for the selected state } - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier andWidth:(CGFloat)width{ if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) { self.textFiled = [[UITextField alloc]initWithFrame:CGRectMake(35, 5, width - 70, 34)]; self.textFiled.borderStyle = UITextBorderStyleRoundedRect; [self addSubview:self.textFiled]; } return self; } @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/W3C/LCCSqliteManager/UI/DataList/LccCell.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
193
```objective-c // // DataEditViewDelegate.h // BigShow1949 // // Created by zhht01 on 16/4/25. // #ifndef DataEditViewDelegate_h #define DataEditViewDelegate_h #import <Foundation/Foundation.h> @protocol ProtocolDelegate <NSObject> //// //@required //- (void)error; // @optional - (void)other; - (void)other2; - (void)other3; @end #endif /* DataEditViewDelegate_h */ ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/W3C/LCCSqliteManager/UI/DataList/DataEditViewDelegate.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
106
```objective-c // // LccDataCell.m // DatabaseMangerDemo // // Created by LccLcc on 15/12/2. // #import "Define.h" #import "LccDataCell.h" #import "LCCSqliteManager.h" @implementation LccDataCell - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier data:(NSArray *)pArray{ NSLog(@"initcell"); if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) { self.backgroundColor = [UIColor colorWithWhite:.9 alpha:.5]; long width = KWidth/pArray.count; for (int i = 0; i < pArray.count; i ++) { UILabel *attributetitle = [[UILabel alloc]initWithFrame:CGRectMake(i * width, 2, width, 40)]; // attributetitle.tag = i+100; attributetitle.text = pArray[i]; [attributetitle setFont:[UIFont systemFontOfSize:14]]; attributetitle.textColor = [UIColor lightGrayColor]; attributetitle.textAlignment = NSTextAlignmentCenter; [self addSubview:attributetitle]; } } return self; } @end ```
/content/code_sandbox/BigShow1949/Classes/12 - DataPersistence(数据持久化)/W3C/LCCSqliteManager/UI/DataList/LccDataCell.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
261