CottonObject 0.0.5

CottonObject 0.0.5

测试已测试
语言语言 Obj-CObjective C
许可协议 MIT
发布日期最后发布2016 年 3 月

Syed Haris AliHermiteer, LLC 维护。



  • 作者
  • Christoph

一个舒适的、舒适的、柔和的包装器,使 JSON(以及其他)网络对象的生活更轻松。

有许多网络端点返回文本块,这些文本块可以通过 RestKit 或 JSONKit 等框架转换为 Cocoa 的 NSDictionary 和 NSArray。不幸的是,需要使用 NSDictionary 的应用程序代码必须使用 NSString 键来提取值。这是易于出错且耗时的,更不用说 Xcode 除非您将其声明为常量,否则不会自动完成键。将此乘以响应中的值的数量,您会很快看到它是多么混乱。

[someNetworkFramework GET:@"blahblahblah"
                parameters:parameters
                   success:^(NetworkOperation* operation,
                             id responseObject)
  {
    NSDictionary* dictionary = responseObject;
    NSString* name = dictionary[@"name"];
    ...
    NSString* type = dictionary[@"type"];
  }];

另一个问题是,无论您的代码期望何种类型,NSDictionary 都会高兴地返回它具有的任何键的值。有很多时候,端点之间会交替使用字符串和数字作为属性,您的应用程序将单纯地开始崩溃。

CottonObject 允许开发者将 NSDictionary 响应快速包装在正式的 Objective-C 类中。这有几个好处:

  1. 因为对象使用 NSDictionary 作为数据存储,它可以通过 NSCoding 协议轻松地进行反序列化和序列化。
  2. 如果您的网络或 API 尚未启动,可以使用从 plists 实例化的字典“模拟”对象。
  3. 为字典提供了类型安全的访问器和设置器。缺失或错误键值的返回为 nil,只要您的代码支持这一点(它始终应该),就可以避免当您的端点结果意外更改时崩溃。
  4. 使用属性名称作为键,消除了声明字符串常量的需要。

它是如何工作的?

技巧是使用 _cmd 变量,这是每个 Objective-C 方法上下文中的一个隐藏实例变量。当合成属性时,编译器创建一个与属性同名的同名方法。您可以用自己的版本覆盖它,因此 CottonObject 添加了一些便利方法来使用 _cmd 变量作为对象的内部字典的键。

IMPORTANT: Note that if you specify the getter in the property declaration, that will be
the name of the getter method.  In this case, you can use the xxxForKey flavor methods and
re-map the value in the dictionary.

如何使用它

// declare a subclass of CottonObject
@interface SampleObject : CottonObject

// declare the property in the .h
@property (nonatomic, readonly) NSString* name;

// implement the getter in the .m
- (NSString*) name
{
  return [self stringForGetter:_cmd];
}

如果由于某些原因,内部字典的值名称与属性名称不同,则可以使用字符串作为键。这有助于纠正客户端和服务器 API 之间的一致性错误。

// declare the property in the .h
@property (nonatomic, readonly) NSString* myName;

// implement the getter in the .m
- (NSString*) name
{
  return [self stringForKey:@"my_name"];
}

如果属性是 NSDictionary(即将字典值作为字典),则可以建立父/子 CottonObject 层次结构。

// declare the child object
@interface Child : CottonObject
...
@end

// declare the parent object with the Child property
@interface Parent : CottonObject

@property (nonatomic, readonly) Child* child;

@end

// implement a getter for the Child
- (Child*) child
{
  return [self objectWithClass:Child.class forKey:NSStringFromSelector(_cmd)];
}

但是读写属性怎么办?嗯,CottonObject可以在这方面帮助您。它提供了一些方便的API来设置原始和NSObject子类。

// declare a read-write property
@property (nonatomic, copy) NSString* name;

// implement getter
- (NSString*) name
{
  return [self stringForGetter:_cmd];
}

// implement setter
- (void) setName:(NSString*)name
{
  [self setString:name forSetter:_cmd];
}

查看CottonObject示例Xcode项目。它声明了SampleObject,并展示了如何从NSDictionary plist中实例化它。

如何安装它

只需下载CottonObject.h和CottonObject.c,然后将它们添加到您的项目中。CottonObject使用ARC,因此如果您的项目不使用ARC,请按照以下说明操作http://www.codeography.com/2011/10/10/making-arc-and-non-arc-play-nice.html.

CocoaPods支持即将推出!