LoginSignup
19
18

More than 5 years have passed since last update.

サーバの JSON テキストから Objective-C のインスタンスを生成するライブラリ、SimpleRemoteObject を公開しました。

Last updated at Posted at 2013-03-16

先日、NSRails 的なクラスを自前で作ってみた にて作っていたライブラリですが、自分のプロジェクトでは結構役に立っているので、github に公開しました。

基本は以前の記事から大きくは変わっていませんが、以下のように使えます。

例えば、http://your_server/users.json にアクセスすると以下のようなテキストが帰ってくる場合

your_server/users.json
{
meta: {
 limit: 20,
 next: null,
 offset: 0,
 previous: null,
 total_count: 3
},
objects: [
 {
   id: 1,
   name: "Daniel",
   email: "daniel@example.com",
   age: 25
 },
 {
   id: 2,
   name: "Mario",
   email: "mario@example.com",
   age: 30
 },
 {
   id: 3,
   name: "Hal",
   email: "hal@example.com",
   age: 32
 }
]
}

iOS 側では以下のようなクラスを作成します。

User.h
#import <SimpleRemoteObject/SRSimpleRemoteObject.h>
@interface User : SRSimpleRemoteObject
@property(nonatomic,retain) NSString *name;
@property(nonatomic,retain) NSString *email;
@property(nonatomic) int age;
@end
User.m
#import "User.h"

@implementation Tag
+(NSString *)representUrl{
 return @"users.json"; // server path
}
+(NSString *)resultKey{
 return @"objects"; // key of target JSON object
}
@end

AppDelegate などで、SRRemoteConfig クラスにサーバのアドレスを設定します

YourAppDelegate.h
#import <SimpleRemoteObject/SRSimpleRemoteObject.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
 [SRRemoteConfig defaultConfig].baseurl = SERVER_URL;

 // Override point for customization after application launch.
 return YES;
}

あとは、必要な場所で fetchAsync:^(NSArray *allRemote, NSError *error) を呼び出すだけです。

[User fetchAsync:^(NSArray *allRemote, NSError *error) {
 if (error){
     //Do error handling
 }else{
     for (User* user in allRemote){
         NSLog(@"my name is:%@",user.name);
     }
 }
}];

サーバのURIに動的にパラメータを付与したり、POSTメソッドを叩いたりといったことにも対応しています。

CocoaPod に対応していますので、インストールも簡単です。
詳しくは githubのプロジェクトをご確認ください。

ドキュメントが追いついていませんが、テストコードを見るとだいたいどんなことができるのかわかると思います。

エラーハンドリングとかが適当なので、少し強化する予定です。
また、今のところ参照のみなので、そのうち CRUD サポートも行う予定です。

コントリビューターも募集中です!Pull Request お待ちしております!!

19
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
18