PFObject子类:重写动态getter的正确方法



我使用PFObject的以下子类:

//HEADER FILE
#import <Parse/Parse.h>
@interface ParseMenuItem : PFObject <PFSubclassing>
@property (nonatomic, strong) NSString * name;
@property (nonatomic, strong) NSString * menuItemDescription;
@property (nonatomic, strong) NSArray * menuPortions; //Some other PFObjects...
@property (nonatomic, strong) NSArray * categories; //NSStrings
//...
@end

//IMPLEMENTATION FILE
#import <Parse/PFObject+Subclass.h>
#import "ParseMenuItem.h"
@implementation ParseMenuItem
@dynamic name, menuItemDescription, menuPortions, categories;
+ (NSString*) parseClassName {
    return @"MenuItem";
}
//...
@end

每次我尝试访问menuItem.categoriesmenuItem.menuPortions(其中menuItem是类型为ParseMenuItem的已提取对象)时,都会引发异常Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Key "categories" / "menuPortions" has no data. Call fetchIfNeeded before getting its value.'

如何自定义这些属性的getter,以便在需要时自动获取数据?

我不知道动态生成的getter是什么样子的,所以我不知道我必须写些什么才能用一些自定义的getter来替换它们。

有没有一种方法可以在我提供的方法中调用动态生成的方法?

在访问键之前,您需要先检查键是否已定义/是否有数据。让它在getter中获取数据是一个不错的想法,但它必须是异步的,因此除非您提供块,否则它无法返回值。

您可以定义一个getter,它至少可以安全地进行检查而不抛出:

-(NSString *) menuItemDescription {
  if (menuItemDescription) {
    return menuItemDescription;
  }
  return nil;
}

edit:你试过在setter中进行阻塞获取吗?类似于:

-(NSArray *) categories {
  if (!categories) {
    [self fetchIfNeeded];
  }
  if (!categories) {
    return nil;
  }
  return categories;
}

最新更新