• Stars
    star
    1,068
  • Rank 43,257 (Top 0.9 %)
  • Language
    Objective-C
  • License
    Other
  • Created over 12 years ago
  • Updated about 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

AutoCoding is a category on NSObject that provides automatic support for NSCoding and NSCopying to every object.

Build Status

Purpose

AutoCoding is a category on NSObject that provides automatic support for NSCoding to any object. This means that rather than having to implement the initWithCoder: and encodeWithCoder: methods yourself, all the model classes in your app can be saved or loaded from a file without you needing to write any additional code.

Of course no automated system can read your mind, so AutoCoding does place certain restrictions on how you design your classes; For example, you should avoid using structs that are not already NSCoding-compliant via NSValue.

Use of AutoCoding is by no means and all-or-nothing decision. You are free to implement your own NSCoding or NSCopying methods on any class in your project and they will simply override the automatically generated methods.

Supported OS & SDK Versions

  • Supported build target - iOS 11.0 / Mac OS 10.12 (Xcode 9.0)
  • Earliest supported deployment target - iOS 9.0 / Mac OS 10.10
  • Earliest compatible deployment target - iOS 4.3 / Mac OS 10.6

NOTE: 'Supported' means that the library has been tested with this version. 'Compatible' means that the library should work on this OS version (i.e. it doesn't rely on any unavailable SDK features) but is no longer being tested for compatibility and may require tweaking or bug fixes to run correctly.

ARC Compatibility

AutoCoding is compatible with both ARC and non-ARC compile targets.

Thread Safety

AutoCoding is fully thread-safe.

Installation

To use the AutoCoding category in your project, just drag the AutoCoding.h and .m files into your project.

Security

As of version 2.0, AutoCoding supports the NSSecureCoding protocol automatically, and returns YES for the +supportsSecureCoding method for all objects by default. In addition to this, assuming you do not override +supportsSecureCoding to return NO, AutoCoding will automatically throw an exception when attempting to decode a class whose type doesn't match the property it is being assigned to. This makes it much harder for a malicious party to craft an NSCoded file that, when loaded by your app, will cause it to execute code that you didn't intend it to.

NSCopying

As of version 2.1, NSCopying is no longer implemented automatically, as this caused some compatibility problems with Core Data NSManagedObjects. If you wish to implement copying, this can be done quite easily by looping over the codableProperties keys and copying those properties individually to a new instance of the object (as follows):

- (id)copyWithZone:(id)zone
{
    id copy = [[[self class] alloc] init];
    for (NSString *key in self.codableProperties)
    {
        [copy setValue:[self valueForKey:key] forKey:key];
    }
    return copy;
}

In order to properly support NSCopying, you should also override the -hash and -isEqual: methods for any object you intend to use with copying, so that a copied object has the same hash value and is equal to the original.

Tips

  1. To exclude certain properties of your object from being encoded, you can do so in any of the following ways:

    • Only use an ivar, without declaring a matching @property.
    • Change the name of the ivar to something that is not KVC compliant (i.e. not the same as the property, or the property name with an _ prefix). You can do this using the @synthesize method, e.g. @synthesize foo = unencodableFoo;
    • Override the +codableProperties method
  2. If you want to perform initialisation of the class post or prior to the properties being loaded via NSCoding, override the setWithCoder: method and call the super-implementation before or after applying your own logic, like this:

     - (void)setWithCoder:(NSCoder *)coder
     {
         //pre-initialisation
         [super setWithCoder:coder];
         //post-initialisation
     }
    

    Note that unlike in previous versions, the init method is not called when using initWithCoder:.

  3. If you want to perform some cleanup or post-processing or substitute a different object after the object has been loaded via NSCoding, you can use the awakeAfterUsingCoder: method, which is defined in the NSObject class reference.

  4. You can add additional coding/decoding logic by overriding the setWithCoder: and/or encodeWithCoder: methods. As long as you call the [super ...] implementation, the auto-coding will still function.

  5. If you wish to substitute a different class for properties of a given type - for example if you have changed the name of a class but wish to retain compatibility with files saved using the old class name, you can substitute a different class for a given name by using the [NSKeyedUnArchiver setClass:forClassName:] method.

  6. If you have properties of a type that doesn't support NSCoding (e.g. a struct), and you wish to code them yourself by applying a conversion function, mark the property as unecodable by changing its ivar name and override the setWithCoder: and encodeWithCoder: methods (remembering to call the super-implementations of those methods to automatically load and save the other properties of the object). Like this:

     @synthesize uncodableProperty = noencode_uncodableProperty; //non-KVC-compliant name
     
     - (void)setWithCoder:(NSCoder *)coder
     {
         [super setWithCoder:coder];
         self.uncodableProperty = DECODE_VALUE([coder decodeObjectForKey:@"uncodableProperty"]);
     }
     
     - (void)encodeWithCoder:(NSCoder *)coder
     {
         [super encodeWithCoder:coder];
         [coder encodeObject:ENCODE_VALUE(self.newProperty) forKey:@"uncodableProperty"];
     }
    
  7. If you have changed the name of a property, but want to check for the existence of the old key name for backwards compatibility, override the setWithCoder: method and add a check for the old property as follows:

     - (void)setWithCoder:(NSCoder *)coder
     {
         [super setWithCoder:coder];
         self.newProperty = [coder objectForKey:@"oldProperty"] ?: self.newProperty;
     }
    
  8. If you have changed the name of a property, but want to load and save it using the old key name for backwards compatibility, give the new property a non-KVC-compliant ivar name and override the setWithCoder:/encodeWithCoder: methods to save and load the property using the old name (remembering to call the super-implementations of those methods to automatically load and save the other properties of the object). Like this:

     @synthesize newProperty = noencode_newProperty; //non-KVC-compliant name
     
     - (void)setWithCoder:(NSCoder *)coder
     {
         [super setWithCoder:coder];
         self.newProperty = [coder objectForKey:@"oldProperty"];
     }
     
     - (void)encodeWithCoder:(NSCoder *)coder
     {
         [super encodeWithCoder:coder];
         [coder encodeObject:self.newProperty forKey:@"oldProperty"];
     }
    

Release Notes

Version 2.2.3

  • Updated for Xcode 9
  • Fixed nullability annotation error in header

Version 2.2.2

  • Fixed warnings on latest Xcode
  • Added nullability and lightweight generics
  • Moved method and property documentation into the header file

Version 2.2.1

  • Added missing <Foundation/Foundation.h> import, required on Xcode 6.x

Version 2.2

  • Now supports @dynamic properties, allowing AutoCoding to be used with NSManagedObjects
  • Added support for additional integer types
  • Fixed unit tests

Version 2.1

  • Removed automatic NSCopying implementation (see README for details)
  • The +codableProperties method will no longer include properties whose ivars are not KVC compliant, even if they are readwrite. This makes it easier to mark readwrite properties as uncodable without needing to override methods
  • The +uncodableProperties method is now deprecated
  • dictionaryRepresentation method will now no longer include NSNull entries for nil values (these will simply be omitted from the result instead)
  • Now complies with the -Weverything warning level

Version 2.0.3

  • Now complies with the -Wextra warning level

Version 2.0.2

  • Fixed longstanding issue where uncodableProperties / uncodableKeys was ignored for readonly properties.

Version 2.0.1

  • Fixed bug where AutoCoding's NSCopying implementation was not compatible with properties using copy semantics due to lack of a copyWithZone: implementation.
  • Now returns YES for respondsToSelector:@selector(copyWithZone:).

Version 2.0

  • AutoCoding now implements the NSSecureCoding protocol automatically
  • AutoCoding now detects property types automatically and throws an exception by default if encoded classes to not match the expected type
  • Autocoding 2.0 is data-compatible with previous releases, but may require code changes when upgrading.

Version 1.3.1

  • Fixed issue with CoreData where AutoCoding's copyWithZone: implementation conflicted with NSManagedObjects
  • Due to changes in the automatic NSCopying implementation, calling [super copyWithZone:] will no longer work. If you need to do this, override the copy method and call [super copy] instead
  • Added Podspec file

Version 1.3

  • AutoCoding no longer attempts to encode virtual properties. Only ivar-backed properties will be encoded
  • Added dictionaryRepresentation method for quickly accessing all properties of a class
  • The codableKeys and uncodableKeys methods are now class methods, allowing them to be used more easily in factory methods
  • The class-level codable/uncodableKeys methods now only return the properties for the class on which they are called, not all of its superclasses as well
  • It is no longer necessary to call [super codableKeys] or [super uncodableKeys] and merge arrays when overriding the codableKeys or uncodableKeys class methods on a subclass (overriding the codableKeys instance method is not recommended)

Version 1.2.1

  • writeToFile:atomically: method now returns a BOOL to indicate success
  • Changed category file names

Version 1.2

  • Read-only properties can now be copied and coded as long as they have a KVC compliant ivar (i.e. one whose name matches the property or the property with the _ prefix)
  • initWithCoder: no longer calls [self init], in compliance with Apple docs
  • codableKeys method now uses caching for better performance
  • Exposed previously private setWithCoder: method used by BaseModel library

Version 1.1.2

  • Switched constructor to return new type-safe instancetype instead of id, making it easier to use dot-syntax property accessors on loaded instances.

Version 1.1.1

  • Read-only properties are now excluded from codableKeys
  • Added unit tests

Version 1.1

  • Added automatic NSCopying implementation
  • writeToFile now obeys the useAuxiliaryFile parameter

Version 1.0

  • Initial release

More Repositories

1

iCarousel

A simple, highly customisable, data-driven 3D carousel for iOS and Mac OS
Objective-C
11,999
star
2

SwiftFormat

A command-line tool and Xcode Extension for formatting Swift code
Swift
7,781
star
3

FXBlurView

[DEPRECATED]
Objective-C
4,942
star
4

iRate

[DEPRECATED]
Objective-C
4,100
star
5

FXForms

[DEPRECATED]
Objective-C
2,926
star
6

SwipeView

SwipeView is a class designed to simplify the implementation of horizontal, paged scrolling views on iOS. It is based on a UIScrollView, but adds convenient functionality such as a UITableView-style dataSource/delegate interface for loading views dynamically, and efficient view loading, unloading and recycling.
Objective-C
2,646
star
7

layout

A declarative UI framework for iOS
Swift
2,231
star
8

iVersion

[DEPRECATED]
Objective-C
1,947
star
9

NullSafe

NullSafe is a simple category on NSNull that returns nil for unrecognised messages instead of throwing an exception
Objective-C
1,943
star
10

RetroRampage

Tutorial series demonstrating how to build a retro first-person shooter from scratch in Swift
Swift
1,486
star
11

XMLDictionary

[DEPRECATED]
Objective-C
1,139
star
12

GZIP

A simple NSData category for gzipping/unzipping data in iOS and Mac OS
Objective-C
983
star
13

FastCoding

A faster and more flexible binary file format replacement for NSCoding, Property Lists and JSON
C
976
star
14

AsyncImageView

[DEPRECATED]
Objective-C
906
star
15

iConsole

[DEPRECATED]
Objective-C
859
star
16

Expression

A cross-platform Swift library for evaluating mathematical expressions at runtime
Swift
822
star
17

FXLabel

[DEPRECATED]
Objective-C
816
star
18

CountryPicker

CountryPicker is a custom UIPickerView subclass that provides an iOS control allowing a user to select a country from a list. It can optionally display a flag next to each country name, and the library includes a set of 249 high-quality, public domain flag images from FAMFAMFAM (http://www.famfamfam.com/lab/icons/flags/) that have been painstakingly re-named by country code to work with the library.
Objective-C
740
star
19

Euclid

A Swift library for creating and manipulating 3D geometry
Swift
637
star
20

SoundManager

Simple sound and music player class for playing audio on Mac and iPhone
Objective-C
630
star
21

FXImageView

FXImageView is a class designed to simplify the application of common visual effects such as reflections and drop-shadows to images, and also to help the performance of image loading by handling it on a background thread.
Objective-C
628
star
22

Base64

[DEPRECATED]
Objective-C
578
star
23

FXKeychain

[DEPRECATED]
Objective-C
554
star
24

MustOverride

Provides a macro that you can use to ensure that a method of an abstract base class *must* be overriden by its subclasses.
Objective-C
523
star
25

LayerSprites

LayerSprites is a library designed to simplify the use of sprite sheets (image maps containing multiple sub-images) in UIKit applications without using OpenGL or 3rd-party game libraries. Can load sprite sheets in the Coco2D format.
Objective-C
504
star
26

GLView

[DEPRECATED]
Objective-C
477
star
27

FXNotifications

An alternative API for NSNotificationCenter that doesn't suck
Objective-C
392
star
28

ShapeScript

The ShapeScript 3D modeling app for macOS and iOS
Swift
391
star
29

LRUCache

LRUCache is an open-source replacement for NSCache that behaves in a predictable, debuggable way
Swift
378
star
30

VectorMath

A Swift library for Mac and iOS that implements common 2D and 3D vector and matrix functions, useful for games or vector-based graphics
Swift
367
star
31

ReflectionView

[DEPRECATED]
Objective-C
359
star
32

Swiftenstein

Simple Wolfenstein 3D clone written in Swift
Swift
359
star
33

JPNG

JPNG is a bespoke image file format that combines the compression benefits of JPEG with the alpha channel support of a PNG file. The JPNG library provides an Objective-C implementation of this format along with transparent JPNG loading support for iOS and Mac OS.
Objective-C
340
star
34

StandardPaths

StandardPaths is a category on NSFileManager for simplifying access to standard application directories on iOS and Mac OS and abstracting the iCloud backup flags on iOS. It also provides support for working with device-specific file suffixes, such as the @2x suffix for Retina displays, or the -568h suffix for iPhone 5 and can optionally swizzle certain UIKit methods to support these suffixes more consistently.
Objective-C
336
star
35

ViewUtils

ViewUtils is a collection of category methods designed that extend UIView with all the handy little properties and functionality that you always wished were built-in to begin with.
Objective-C
324
star
36

FXPageControl

Simple, drop-in replacement for the iPhone UIPageControl that allows customisation of the dot colour, size and spacing.
Objective-C
298
star
37

BaseModel

BaseModel provides a base class for building model objects for your iOS or Mac OS projects. It saves you the hassle of writing boilerplate code, and encourages good practices by reducing the incentive to cut corners in your model implementation.
Objective-C
288
star
38

OrderedDictionary

This library provides OrderedDictionary and MutableOrderedDictionary subclasses.
Objective-C
278
star
39

ColorUtils

[DEPRECATED]
Objective-C
256
star
40

Tribute

A command-line tool for tracking Swift project licenses
Swift
246
star
41

OSNavigationController

[DEPRECATED]
Objective-C
233
star
42

Consumer

Mac and iOS library for parsing structured text
Swift
226
star
43

iNotify

[DEPRECATED]
Objective-C
225
star
44

FPSControls

An experimental implementation of touch-friendly first-person shooter controls using SceneKit and Swift
Swift
215
star
45

OSCache

OSCache is an open-source re-implementation of NSCache that behaves in a predictable, debuggable way.
Objective-C
200
star
46

Chess

A simple Chess game for iOS, written in Swift
Swift
177
star
47

RequestQueue

[DEPRECATED]
Objective-C
174
star
48

FXReachability

Lightweight reachability class for Mac and iOS
Objective-C
173
star
49

Sprinter

A library for formatting strings on iOS and macOS
Swift
166
star
50

CryptoCoding

CryptoCoding is a superset of the NSCoding protocol that allows for simple, seamless AES encryption of any NSCoding-compatible object.
Objective-C
148
star
51

RequestUtils

A collection of category methods designed to simplify the process of HTTP request construction and manipulation in Cocoa.
Objective-C
142
star
52

CubeController

CubeController is a UIViewController subclass that can be used to create a rotating 3D cube navigation.
Objective-C
142
star
53

HTMLLabel

[DEPRECATED]
Objective-C
139
star
54

NSOperationStack

[DEPRECATED]
Objective-C
118
star
55

SVGPath

Cross-platform Swift library for parsing SVGPath strings
Swift
111
star
56

HRCoder

HRCoder is a replacement for the NSKeyedArchiver and NSKeyedUnarchiver classes that uses a human-readable/editable format that can easily be stored in a regular Plist or JSON file.
Objective-C
104
star
57

iPrompt

[DEPRECATED]
Objective-C
99
star
58

Presentations

Code samples and projects for presentations that I have given
Objective-C
98
star
59

FXPhotoEditView

[DEPRECATED]
Objective-C
92
star
60

StackView

StackView is a class designed to simplify the implementation of vertical stacks of views on iOS. You can think of it as a bit like a simplified version of UITableView.
Objective-C
73
star
61

WebContentView

[DEPRECATED]
Objective-C
69
star
62

StringCoding

StringCoding is a simple Mac/iOS library for setting object properties of any type using string values. It can automatically detect the property type and attempt to interpret the string as the right kind of value. It's particularly oriented towards iOS app theming (see README for details).
Objective-C
57
star
63

ArrayUtils

[DEPRECATED]
Objective-C
49
star
64

Swune

Swift/UIKit reimplementation of the Dune II RTS game
Swift
46
star
65

Parsing

Supporting code for my talk entitled "Parsing Formal Languages with Swift"
Swift
42
star
66

MACAddress

[DEPRECATED]
Objective-C
39
star
67

FXParser

[DEPRECATED]
Objective-C
34
star
68

RotateView

Objective-C
34
star
69

RandomSequence

A class for creating independent, repeatable pseudorandom number sequences on Mac and iOS
Objective-C
28
star
70

FloatyBalloon

This is the source code for a simple game called Floaty Balloon, based on the gameplay of Flappy Bird. It was created as a tutorial for http://iosdevelopertips.com
Objective-C
25
star
71

Concurrency

Full source code for a simple currency calculator app
Objective-C
15
star
72

FXJSON

[DEPRECATED]
Objective-C
15
star
73

PNGvsJPEG

This is a simple benchmark app to compare JPEG vs PNG loading performance on iOS. Spoiler: JPEG wins.
Objective-C
6
star