Convert Figma logo to code with AI

pinterest logoPINCache

Fast, non-deadlocking parallel object cache for iOS, tvOS and OS X

2,657
361
2,657
30

Top Related Projects

Smooth asynchronous user interfaces for iOS apps.

Asynchronous image downloader with cache support as a UIImageView category

A lightweight generic cache for iOS written in Swift with extra love for images.

8,040

Image loading system

A lightweight, pure-Swift library for downloading and caching images from the web.

A delightful networking framework for iOS, macOS, watchOS, and tvOS.

Quick Overview

PINCache is a fast, thread-safe key/value store for iOS and macOS. It's designed to persist objects to disk and memory, providing a simple interface for caching data. PINCache supports both synchronous and asynchronous operations, making it versatile for various use cases.

Pros

  • Thread-safe and optimized for performance
  • Supports both memory and disk caching
  • Offers synchronous and asynchronous APIs
  • Customizable cache limits and expiration policies

Cons

  • Limited to iOS and macOS platforms
  • May require additional setup for complex caching scenarios
  • Documentation could be more comprehensive
  • Lacks built-in support for certain advanced caching features (e.g., cache invalidation based on complex rules)

Code Examples

  1. Storing and retrieving an object:
let cache = PINCache.shared
cache.setObject("Hello, World!" as NSString, forKey: "greeting")
if let greeting = cache.object(forKey: "greeting") as? String {
    print(greeting) // Output: Hello, World!
}
  1. Asynchronous object retrieval:
cache.object(forKey: "user_data") { (cache, key, object) in
    if let userData = object as? [String: Any] {
        print("User data retrieved: \(userData)")
    }
}
  1. Setting a custom expiration date:
let expirationDate = Date().addingTimeInterval(3600) // 1 hour from now
cache.setObject(myObject, forKey: "temporary_data", withExpiration: expirationDate)

Getting Started

  1. Install PINCache using CocoaPods by adding the following to your Podfile:
pod 'PINCache'
  1. Import PINCache in your Swift file:
import PINCache
  1. Create a cache instance or use the shared instance:
let cache = PINCache.shared
// or
let customCache = PINCache(name: "CustomCache")
  1. Start using the cache to store and retrieve objects:
cache.setObject(myObject, forKey: "myKey")
let retrievedObject = cache.object(forKey: "myKey")

Competitor Comparisons

Smooth asynchronous user interfaces for iOS apps.

Pros of AsyncDisplayKit

  • More comprehensive UI framework, offering advanced layout and rendering capabilities
  • Designed for asynchronous UI operations, potentially improving performance for complex interfaces
  • Provides a rich set of UI components and tools for building responsive apps

Cons of AsyncDisplayKit

  • Steeper learning curve due to its more complex architecture
  • Larger codebase and potentially higher memory footprint
  • Less focused on caching specifically, as it's a broader UI framework

Code Comparison

AsyncDisplayKit (now Texture) example:

ASDisplayNode *node = [[ASDisplayNode alloc] init];
node.backgroundColor = [UIColor redColor];
node.bounds = CGRectMake(0, 0, 100, 100);
[self.view addSubnode:node];

PINCache example:

[PINCache.sharedCache setObject:myObject forKey:@"myKey"];
id cachedObject = [PINCache.sharedCache objectForKey:@"myKey"];

Summary

AsyncDisplayKit (now known as Texture) is a more comprehensive UI framework focused on asynchronous rendering and layout, while PINCache is a lightweight caching solution. AsyncDisplayKit offers more advanced UI capabilities but comes with increased complexity, whereas PINCache provides a simpler, focused approach to caching objects in memory and on disk.

Asynchronous image downloader with cache support as a UIImageView category

Pros of SDWebImage

  • More comprehensive image loading and caching solution
  • Supports animated images (GIF, APNG, WebP)
  • Extensive plugin system for customization

Cons of SDWebImage

  • Larger codebase and potentially higher memory footprint
  • Steeper learning curve due to more features and options

Code Comparison

SDWebImage:

let imageView = UIImageView()
imageView.sd_setImage(with: URL(string: "https://example.com/image.jpg"))

PINCache:

PINCache.shared.object(forKey: "imageKey") { (cache, key, object) in
    if let image = object as? UIImage {
        imageView.image = image
    }
}

Key Differences

  • SDWebImage focuses on image loading and caching, while PINCache is a general-purpose caching solution
  • SDWebImage provides more image-specific features out of the box
  • PINCache offers a simpler API for basic caching needs

Use Cases

  • Choose SDWebImage for complex image loading requirements in iOS apps
  • Opt for PINCache when a lightweight, general-purpose caching solution is needed

Community and Maintenance

  • Both projects are actively maintained and have strong community support
  • SDWebImage has a larger user base and more frequent updates due to its specialized focus

A lightweight generic cache for iOS written in Swift with extra love for images.

Pros of HanekeSwift

  • Lightweight and focused specifically on image caching and processing
  • Built-in support for image resizing and filtering
  • Simple API with a fluent interface for easy integration

Cons of HanekeSwift

  • Less actively maintained compared to PINCache
  • Limited to Swift projects, while PINCache supports both Objective-C and Swift
  • Fewer advanced features like background fetching or disk caching customization

Code Comparison

HanekeSwift:

let cache = Shared.imageCache
cache.fetch(URL: url).onSuccess { image in
    imageView.image = image
}

PINCache:

PINCache.shared.object(forKey: key) { (cache, key, object) in
    if let image = object as? UIImage {
        imageView.image = image
    }
}

Both libraries offer simple APIs for caching and retrieving objects, but HanekeSwift provides a more image-specific interface with built-in URL fetching. PINCache offers a more general-purpose caching solution that can handle various types of objects.

HanekeSwift is ideal for Swift projects focused on image caching and processing, while PINCache is better suited for more complex caching needs across both Objective-C and Swift codebases.

8,040

Image loading system

Pros of Nuke

  • More comprehensive image loading and caching solution, offering advanced features like prefetching and progressive image loading
  • Better performance optimization, including smarter memory caching and disk caching strategies
  • Actively maintained with regular updates and improvements

Cons of Nuke

  • Steeper learning curve due to more complex API and advanced features
  • Larger codebase and potentially higher memory footprint
  • May be overkill for simpler image caching needs

Code Comparison

Nuke:

let pipeline = ImagePipeline.shared
pipeline.loadImage(with: URL(string: "https://example.com/image.jpg")!) { result in
    switch result {
    case .success(let response): imageView.image = response.image
    case .failure(let error): print("Failed to load image: \(error)")
    }
}

PINCache:

[[PINRemoteImageManager sharedImageManager] downloadImageWithURL:[NSURL URLWithString:@"https://example.com/image.jpg"]
                                                        options:0
                                                   progressImage:nil
                                                      completion:^(PINRemoteImageManagerResult *result) {
    if (result.image) {
        imageView.image = result.image;
    }
}];

Both libraries provide efficient image caching solutions, but Nuke offers a more modern, Swift-centric approach with additional features for advanced image loading scenarios. PINCache, while simpler, may be more suitable for basic caching needs and Objective-C projects.

A lightweight, pure-Swift library for downloading and caching images from the web.

Pros of Kingfisher

  • More comprehensive image loading and caching solution, specifically designed for iOS/macOS
  • Built-in support for image processing and filters
  • Active development and frequent updates

Cons of Kingfisher

  • Larger library size, which may impact app size
  • Steeper learning curve due to more features and options

Code Comparison

Kingfisher:

let url = URL(string: "https://example.com/image.jpg")
imageView.kf.setImage(with: url)

PINCache:

NSURL *url = [NSURL URLWithString:@"https://example.com/image.jpg"];
[PINRemoteImageManager.sharedInstance downloadImageWithURL:url completion:^(PINRemoteImageManagerResult *result) {
    imageView.image = result.image;
}];

Summary

Kingfisher is a more feature-rich image loading and caching library specifically designed for iOS and macOS, offering built-in image processing capabilities. It has a simpler API for basic usage but may have a steeper learning curve for advanced features. PINCache, on the other hand, is a more lightweight and general-purpose caching solution that can be used for various types of data, not just images. It may be more suitable for projects that require a simpler caching mechanism or need to cache different types of objects.

A delightful networking framework for iOS, macOS, watchOS, and tvOS.

Pros of AFNetworking

  • Comprehensive networking library with features beyond caching
  • Widely adopted and well-maintained by the community
  • Supports a broader range of networking tasks (e.g., HTTP requests, authentication)

Cons of AFNetworking

  • Larger footprint and potentially more complex for simple caching needs
  • May include unnecessary features if only caching is required
  • Less focused on optimizing cache performance compared to PINCache

Code Comparison

PINCache:

[PINCache.sharedCache setObject:object forKey:key];
id cachedObject = [PINCache.sharedCache objectForKey:key];

AFNetworking:

NSURLCache *cache = [NSURLCache sharedURLCache];
[cache setMemoryCapacity:10 * 1024 * 1024];
[cache setDiskCapacity:50 * 1024 * 1024];

Summary

AFNetworking is a comprehensive networking library that includes caching capabilities, while PINCache is specifically designed for efficient object caching. AFNetworking offers a broader range of networking features but may be overkill for simple caching needs. PINCache, on the other hand, focuses on optimizing cache performance and provides a simpler API for object caching. The choice between the two depends on the specific requirements of your project and whether you need additional networking functionality beyond caching.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

PINCache

CocoaPods Carthage compatible Build status

Fast, non-deadlocking parallel object cache for iOS and OS X.

PINCache is a fork of TMCache re-architected to fix issues with deadlocking caused by heavy use. It is a key/value store designed for persisting temporary objects that are expensive to reproduce, such as downloaded data or the results of slow processing. It is comprised of two self-similar stores, one in memory (PINMemoryCache) and one on disk (PINDiskCache), all backed by GCD and safe to access from multiple threads simultaneously. On iOS, PINMemoryCache will clear itself when the app receives a memory warning or goes into the background. Objects stored in PINDiskCache remain until you trim the cache yourself, either manually or by setting a byte or age limit.

PINCache and PINDiskCache accept any object conforming to NSCoding. Put things in like this:

Objective-C

UIImage *img = [[UIImage alloc] initWithData:data scale:[[UIScreen mainScreen] scale]];
[[PINCache sharedCache] setObject:img forKey:@"image" block:nil]; // returns immediately

Swift

let img = UIImage(data: data, scale:UIScreen.main.scale)
PINCache.shared().setObject(img, forKey: "img")

Get them back out like this:

Objective-C

[[PINCache sharedCache] objectForKeyAsync:@"image" block:^(PINCache *cache, NSString *key, id object) {
    UIImage *image = (UIImage *)object;
    NSLog(@"image scale: %f", image.scale);
}];

Swift

PINCache.shared().object(forKey: "image") { (cache, key, object) in
    if let image = object as? UIImage {
        print("image scale: %f", image.scale)
    }
}

Both PINMemoryCache and PINDiskCache use locks to protect reads and writes. PINCache coordinates them so that objects added to memory are available immediately to other threads while being written to disk safely in the background. Both caches are public properties of PINCache, so it's easy to manipulate one or the other separately if necessary.

Collections work too. Thanks to the magic of NSKeyedArchiver, objects repeated in a collection only occupy the space of one on disk:

Objective-C

NSArray *images = @[ image, image, image ];
[[PINCache sharedCache] setObject:images forKey:@"images"];
NSLog(@"3 for the price of 1: %d", [[[PINCache sharedCache] diskCache] byteCount]);

Swift

// In Swift, Array, String, and Dictionary are all value types.
let images = [image, image, image] as NSArray // Cast to NSArray
PINCache.shared.setObject(images, forKey: "images")
print("3 for the prices of 1: %d", PINCache.shared.diskCache.byteCount)

Installation

Manually

Download the latest tag and drag the PINCache folder into your Xcode project.

Install the docs by double clicking the .docset file under docs/, or view them online at cocoadocs.org

Git Submodule

git submodule add https://github.com/pinterest/PINCache.git
git submodule update --init

CocoaPods

Add PINCache to your Podfile and run pod install.

Carthage

Add the following line to your Cartfile and run carthage update --platform ios. Then follow this instruction of Carthage to embed the framework.

github "pinterest/PINCache"

Requirements

PINCache requires iOS 12.0, tvOS 12.0, watchOS 4.0 or macOS 10.13 and greater.

Contact

Garrett Moon

License

Copyright 2013 Tumblr, Inc. Copyright 2015 Pinterest, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.