使用NSPredicate查询RLMObject不返回结果

时间:2015-09-02 06:20:05

标签: ios objective-c realm

这是我的Realm模型:

Pet.h

#import <Realm/Realm.h>

@interface Pet : RLMObject

@property NSString *species;

@end

Pet.m

#import "Pet.h"

@implementation Pet

+ (NSString *)primaryKey {
    return @"species";
}

@end

写入领域

- (void)writeCat {
       RLMRealm *realm = [RLMRealm defaultRealm];
       [realm beginWriteTransaction];

       Pet *pet = [[Pet alloc] init];
       pet.species = @"cat";//as Primary Key
      [Pet createOrUpdateInRealm:realm withValue:pet];

      [realm commitWriteTransaction];

      for (Pet *pet in [Pet allObjects]) {

          NSLog(@"pet in realm: %@", pet);
          //prints out: 
          //pet in realm: Pet {species = cat;}
      }
}

从领域查询(在写入数据后)

- (void)queryCat {
    NSPredicate *predicate = [NSPredicate 
                              predicateWithFormat: @"species == %@", @"cat"];
      RLMResults *cat = [Pet objectsWithPredicate:predicate];
      RLMResults *all = [Pet allObjects];

      NSLog(@"cat: %@ and all: %@", cat, all);
      //prints out: 
      //cat: RLMResults <0x7fdeed8e8710> ( )
      //and all: RLMResults <0x7ffa151c6630> ( )
}

修改

我如何调用方法:

 -(void)viewDidLoad{
   [self writeCat];
   [self queryCat];
}

我确实在Realm中写了一些东西,但没有从中查询,

我对查询做了什么错误?

2 个答案:

答案 0 :(得分:0)

试试这个,

RLMResults *allResults = [Pet allObjects];    //getting all objects
allResults = [allResults objectsWhere:@"species contains 'cat'"]; // querying for cat

答案 1 :(得分:0)

  RLMResults *results = [Pet objectsWhere:@"species = 'cat'"];
  if(results.count){
      Pet *foundedPet = results.firstObject;
  }