1
votes

I've been using firebase successfully to read and write data for an iOS app. Now I'm starting to need to store and retrieve more complex objects. I want to make sure I'm proceeding in the correct manner.

I've got a class such as,

@interface MyClass : NSObject

@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *id;

@end

When I write this class into firebase,

MyClass *myClass1 = [[MyClass alloc] init];
myClass1.name = @"Bakery";
myClass1.id = @"1";

[firebase setValue:myClass1];

An exception is thrown,

'Unknown class in payload: MyClass; only NSDictionary and NSArray supported.'

I see in the iOS firebase docs that NSNumber, NSString, NSArray and NSDictionary are listed as the types the setValue: can handle.

Does this mean I can't use setValue:on my classes? Do I need to unwrap my objects into instances of the NSNumber, NSString, NSArray or NSDictionary objects to store data? I was thinking that the iOS firebase implementation would be able to serialize simple objects to save to firebase.

3

3 Answers

0
votes

You have to get your objects into strings, you can write booleans, numbers, and objects, where objects consist of strings, dates, booleans, and numbers that are persisted in Firebase. These seem to be strings, dates, data, real and whole numbers (including booleans).

0
votes

I don't know Firebase, but what about NSData? It seems like it should be able to accept that.

Almost any object can easily be turned into NSData using:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myClass1];

// and the reverse:
myClass1 = [NSKeyedUnarchiver unarchiveObjectWithData:data];

Note you will have to implement <NSCoding> in your class, which is also pretty straightforward (many good tutorials available, have a quick search).

If it can't handle NSData either, I'd file a feature request with them, then convert the NSData object into an NSString:

NSString *dataString = [data base64Encoding]; // this is deprecated in iOS 7 / OS X 10.9. But not available in earlier versions.

NSString *dataString = [data base64EncodedStringWithOptions:0]; // new API
0
votes

You might try using a 3rd party library like Mantle to aid you in serializing/deserializing your objects to/from JSON:

https://github.com/Mantle/Mantle.

That should help with some of the boilerplate you're writing.