• Stars
    star
    104
  • Rank 319,991 (Top 7 %)
  • Language
    Objective-C
  • License
    Other
  • Created about 12 years ago
  • Updated over 6 years ago

Reviews

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

Repository Details

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.

Build Status

Purpose

HRCoder is a replacement for the NSKeyedArchiver and NSKeyedUnarchiver classes. Although the NSKeyedArchiver writes data in the standard Plist format, the structure of the Plist makes it hard to read, and nearly impossible to generate by hand.

The HR stands for Human Readable. HRCoder saves files in a simpler format than NSKeyedArchiver; Standard objects such as strings, dictionaries, arrays, numbers, booleans and binary data are all saved and loaded using the standard Plist primitives, and any other type of object is saved as a simple dictionary, with the addition of a $class key to indicate the object type.

This makes it possible to easily generate HRCoder-compatible Plist files by hand, and then load them using the standard NSCoding protocol. You can also read and manually edit files saved by the HRCoder class without fear of corrupting the file.

The simple dictionary/array-based format used by HRCoding can also be easily stored as JSON, opening up more options for serialisation (NSKeyedArchiver is tied to Plists and cannot easily be used to save as JSON without creating a Plist as an intermediate step).

HRCoder is designed to work with the AutoCoding library (https://github.com/nicklockwood/AutoCoding), which can automatically write the initWithCoder: and encodeWithCoder: methods for your classes. Check out the AutoTodoList example to see how this works.

HRCoder is also designed to work hand-in-hand with the BaseModel library (https://github.com/nicklockwood/BaseModel) which forms the basis for building a powerful model hierarchy for your project with minimal effort. Check the HRTodoList example included in the BaseModel repository for an example of how these libraries can work together.

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.0 / 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

As of version 1.3, HRCoder requires ARC. If you wish to use HRCoder in a non-ARC project, just add the -fobjc-arc compiler flag to the HRCoder.m class file. To do this, go to the Build Phases tab in your target settings, open the Compile Sources group, double-click HRCoder.m in the list and type -fobjc-arc into the popover.

If you wish to convert your whole project to ARC, comment out the #error line in HRCoder.m, then run the Edit > Refactor > Convert to Objective-C ARC... tool in Xcode and make sure all files that you wish to use ARC for (including HRCoder.m) are checked.

Thread Safety

It is not safe to access a single HRCoder instance from multiple threads concurrently, hower using the HRCoder class methods to encode and decode objects is completely thread-safe.

Installation

To use HRCoder, just drag the HRCoder.h and .m files into your project.

HRCoder properties

@property (nonatomic, assign) HRCoderFormat outputFormat;

This property can be used to set the output format when serialising HRCoded objects. Possible values are HRCoderFormatXML, HRCoderFormatJSON and HRCoderFormatBinary. The default value is HRCoderFormatXML, which produces an XML Plist.

HRCoder methods

HRCoder implements the following methods, which mirror those of the NSKeyedArchiver and NSKeyedUnarchiver classes.

+ (id)unarchiveObjectWithPlistOrJSON:(id)plistOrJSON;

Constructs an object tree from an encoded Plist or JSON object and returns it. The plistOrJSON parameter can be any object that is natively supported by the Plist or JSON formats. This would typically be a container object such as an NSDictionary or NSArray. If any other kind of object is supplied it will be returned without modification.

Note that this object need not actually be loaded from a Plist or JSON file you can create such an object programmatically.

+ (id)unarchiveObjectWithData:(NSData *)data;

Loads a serialised plist from an NSData object and returns an unarchived object tree by calling unarchiveObjectWithPlist: on the root object in the file. Supports text, JSON, XML or binary-formatted data. Data is deserialised using mutable containers to ensure that mutability of encoded arrays and dictionaries is preserved. If you'd prefer immutable objects, load the object yourself directly using the NSPropertyListSerialization or NSJSONSerialization classes.

+ (id)unarchiveObjectWithFile:(NSString *)path;

Loads a data file in Plist format and returns an unarchived object tree by calling unarchiveObjectWithData:.

+ (id)archivedPlistWithRootObject:(id)object;

Encodes the passed object as a hierarchy of Plist-compatible objects, and returns it. The resultant object will typically be one of NSDictionary, NSArray, NSString, NSData, NSDate or NSNumber. This object is then safe to pass to NSPropertyListSerialisation for conversion to raw data or saving to a file.

+ (id)archivedJSONWithRootObject:(id)object;

Encodes the passed object as a hierarchy of JSON-compatible objects, and returns it. The resultant object will typically be one of NSDictionary, NSArray, NSString, NSNumber or NSNull. This object is then safe to pass to NSPropertyListSerialisation for conversion to raw data or saving to a file.

+ (NSData *)archivedDataWithRootObject:(id)rootObject;

Encodes the passed object by calling archivedPlistWithRootObject: and then serialises it to data using the XML property list format.

+ (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path;

Encodes the passed object by calling archivedDataWithRootObject: and then saves it to the file path specified. The file is saved atomically to prevent data corruption.

- (id)initForReadingWithData:(NSData *)data;

This method is used for creating an HRCoder instance from an encoded NSData object that can be passed directly to the initWithCoder: method of a class. It is included mostly for compatibility with the NSKeyedUnarchiver class, which has the same method. The data must contain a plist-encoded NSDictionary object. Other root objects types such as NSArray are not supported with this method (you can use the unarchiveObjectWithData: method to load data containing other root object types).

- (id)initForWritingWithMutableData:(NSMutableData *)data;

This method is used to create an HTCoder object for the purpose of writing to a data object. Once you have created the HRCoder instance, you can pass it to the encodeWithCoder: method of an object to encode it. Once you have written an object, calling finishEncoding will write the serialised plist data into the NSMutableData object.

- (void)finishDecoding;

Finishes decoding data that was opened using the initForReadingWithData: method.

- (void)finishEncoding;

When a file has been opened using the initForWritingWithMutableData: method, this will close it off and write the serialised data to the originally specified NSMutableData object.

Plist structure

Any ordinary Plist can be loaded using HECoder and it will behave the same way as if you loaded it using NSPropertyListSerialization. To add custom classes to the Plist, define the object as if it was a dictionary, but add an additional $class key with the class name of the object. For example, this code will result in an ordinary NSDictionary:

<dict>
    <key>coming</key>
    <string>Hello</string>
    <key>going</key>
    <string>Goodbye</string>
</dict>

But this will load an object of class Greetings (assuming that class exists in your project).

<dict>
    <key>$class</key>
    <string>Greetings</string>
    <key>coming</key>
    <string>Hello</string>
    <key>going</key>
    <string>Goodbye</string>
</dict>

Another feature of NSCoding that isn't supported by ordinary Plists is circular references. HRCoding supports this using the an aliasing mechanism. If you want to re-use an object in another place within your object hierarchy, you can do this using the following syntax:

<dict>
    <key>$alias</key>
    <string>path.to.the.object</string>
</dict>

The alias value is a key path to the original object within the hierarchy. To see this in context, here is a simple example of how this would work:

<dict>
    <key>object1</key>
    <string>Hello World</string>
    <key>object2</key>
    <dict>
        <key>$alias</key>
        <string>object1</string>
    </dict>
</dict>

Once loaded, the object1 and object2 properties will both point at the same "Hello World" string instance (not just the same value, but the same actual object). This also works with arrays - just use the array index as the alias key:

<array>
    <string>Hello World</string>
    <dict>
        <key>$alias</key>
        <string>0</string>
    </dict>
</array>

Forward references are permitted in aliases (i.e. aliasing an object which is declared later in the hierarchy), however this should be avoided as possible as it involves inserting HRCoderAliasPlaceholder objects as the object tree is deserialised, and then replacing these later, which incurs a slight performance penalty.

Note that if you are using aliases you should be careful not to call methods on deserialised objects insider your initWithCoder: method, as they may not always be of the expected type until loading is complete.

Release notes

Version 1.3.3

  • Fixed warnings in Xcode 9

Version 1.3.2

  • Fixed crash when encoding binary data in JSON files (affected mutable strings)
  • Fixed some additional warnings in Xcode 6

Version 1.3.1

  • Fixed bug with encoding conditional objects
  • HRCoder can now encode NSData objects as JSON using base 64 encoding

Version 1.3

  • outputFormat enum is now of type HRCoderFormat, and includes JSON as an option
  • When using the JSON output format, NSData and NSDate objects are now encoded in a JSON-compatible format
  • HRCoder can now load data encoded in JSON format
  • Now complies with -Weverything warning level
  • Improved performance when using ARC
  • HRCoder now requires ARC

Version 1.2.3

  • Fixed a bug where objects that override isEqual would be incorrectly aliased
  • Objects of type NSNumber, NSDate and short NSStrings will no longer be aliased
  • Now complies with -Wall and -Wextra warning levels

Version 1.2.2

  • Fixed a bug where objects could be skipped when decoding, depending on the order of items in the plist
  • Added CocoaPods podspec

Version 1.2.1

  • Fixed bug where nested NSDictionaries were not decoded correctly

Version 1.2

  • Added initForReadingWithData: and initForWritingWithMutableData: methods, which improve compatibility with the NSKeyedArchiver/Unarchiver class interfaces.
  • Added outputFormat property for setting the Plist format when saving

Version 1.1.3

  • Fixed analyzer warning due to over-autorelease of decoded object

Version 1.1.2

  • Fixed crash when attempting to archive a nil object property

Version 1.1.1

  • HRCoder now calls the awakeAfterUsingCoder: method on objects after they are unarchived.
  • HRCoder now calls the classForCoder and replacementObjectForCoder: methods on an object prior to archiving.

Version 1.1

  • Added unarchiveObjectWithData: and archivedDataWithRootObject: methods
  • HRCoder now saves in XML format instead of binary by default
  • Now supports 32-bit CPUs on Mac OS 10.6

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,991
star
2

SwiftFormat

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

FXBlurView

[DEPRECATED]
Objective-C
4,941
star
4

iRate

[DEPRECATED]
Objective-C
4,114
star
5

FXForms

[DEPRECATED]
Objective-C
2,929
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,648
star
7

layout

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

iVersion

[DEPRECATED]
Objective-C
1,955
star
9

NullSafe

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

RetroRampage

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

XMLDictionary

[DEPRECATED]
Objective-C
1,139
star
12

AutoCoding

AutoCoding is a category on NSObject that provides automatic support for NSCoding and NSCopying to every object.
Objective-C
1,067
star
13

GZIP

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

FastCoding

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

AsyncImageView

[DEPRECATED]
Objective-C
908
star
16

iConsole

[DEPRECATED]
Objective-C
860
star
17

FXLabel

[DEPRECATED]
Objective-C
817
star
18

Expression

A cross-platform Swift library for evaluating mathematical expressions at runtime
Swift
803
star
19

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
738
star
20

SoundManager

Simple sound and music player class for playing audio on Mac and iPhone
Objective-C
631
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
629
star
22

Euclid

A Swift library for creating and manipulating 3D geometry
Swift
606
star
23

Base64

[DEPRECATED]
Objective-C
578
star
24

FXKeychain

[DEPRECATED]
Objective-C
556
star
25

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
524
star
26

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
505
star
27

GLView

[DEPRECATED]
Objective-C
474
star
28

FXNotifications

An alternative API for NSNotificationCenter that doesn't suck
Objective-C
391
star
29

ShapeScript

The ShapeScript 3D modeling app for macOS and iOS
Swift
383
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
364
star
31

ReflectionView

[DEPRECATED]
Objective-C
360
star
32

Swiftenstein

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

LRUCache

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

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
338
star
35

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
337
star
36

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
325
star
37

FXPageControl

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

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
39

OrderedDictionary

This library provides OrderedDictionary and MutableOrderedDictionary subclasses.
Objective-C
277
star
40

ColorUtils

[DEPRECATED]
Objective-C
257
star
41

Tribute

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

OSNavigationController

[DEPRECATED]
Objective-C
234
star
43

iNotify

[DEPRECATED]
Objective-C
226
star
44

Consumer

Mac and iOS library for parsing structured text
Swift
224
star
45

FPSControls

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

OSCache

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

RequestQueue

[DEPRECATED]
Objective-C
175
star
48

FXReachability

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

Chess

A simple Chess game for iOS, written in Swift
Swift
171
star
50

Sprinter

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

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
52

RequestUtils

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

CubeController

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

HTMLLabel

[DEPRECATED]
Objective-C
139
star
55

NSOperationStack

[DEPRECATED]
Objective-C
117
star
56

SVGPath

Cross-platform Swift library for parsing SVGPath strings
Swift
105
star
57

iPrompt

[DEPRECATED]
Objective-C
99
star
58

Presentations

Code samples and projects for presentations that I have given
Objective-C
99
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
50
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

RotateView

Objective-C
35
star
68

FXParser

[DEPRECATED]
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