2009-01-09 103 views
20

我不知道是否有可能(以及如何)提供的Objective-C类的东西,如:在Objective-C中是否有类似于LINQ的东西?

Person.Select(@"Name").OrderAsc(@"Name").Where(@"Id").EqualTo(1).And(@"Id").NotEqualTo(2).Load<Array> 

这可能是一个项目,我做的非常得心应手。

我喜欢这种编码方式存在于Django & SubSonic。

+2

我很喜欢Objective-C中的LINQ等价物。有人应该写一个! – 2010-05-11 18:08:42

+2

@JonathanSterling - 我有! https://开头github上。com/ColinEberhardt/LinqToObjectiveC – ColinE 2013-02-15 22:01:38

回答

6

简短的回答是Objective-C没有Linq的等价物,但是你可以用一个包装类来混合SQLite,NSPredicate和CoreData调用。您可能对core data guidepredicate guidethis example code感兴趣。

从上面的谓词指南:

NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Employee" 
     inManagedObjectContext:managedObjectContext]; 
[request setEntity:entity]; 
// assume salaryLimit defined as an NSNumber variable 
NSPredicate *predicate = [NSPredicate predicateWithFormat: 
     @"salary > %@", salaryLimit]; 
[request setPredicate:predicate]; 
NSError *error = nil; 
NSArray *array = [managedObjectContext executeFetchRequest:request error:&error]; 
3

我认为,具体到您的例子,这会是可可中的等价物:

NSArray *people = /* array of people objects */ 

NSPredicate *pred = [NSPredicate predicateWithFormat:@"Id = 1 AND Id != 2"]; 
NSSortDescriptor *byName = [[NSSortDescriptor alloc] initWithKey:@"Name" ascending:YES]; 
NSArray *descriptors = [NSArray arrayWithObject:[byName autorelease]]; 

NSArray *matches = [people filteredArrayUsingPredicate:pred]; 
NSArray *sortedMatches = [matches sortedArrayUsingDescriptors:descriptors]; 

NSArray *justNames = [sortedMatches valueForKey:@"Name"]; 

这是一个有点比LINQ例子更详细和我的一些线条可能已经组合起来了,但在我看来这更容易解析。

15

我为Objective C创建了我自己的Linq样式的API,它是available on github。你的具体例子是这个样子:

NSArray* results = [[[people where:^BOOL(id person) { 
           return [person id] == 1 && [person id] != 2; 
          }] 
          select:^id(id person) { 
           return [person name]; 
          }] 
          sort]; 
3

我的项目,LINQ4Obj-C,港口LINQ标准查询经营者的Objective-C。

你可以在github及其docs here找到它。该库也可通过CococaPods获得。

该项目的源代码是根据标准的MIT许可证提供的。

你的例子将如下这样:

id results = [[[people linq_where:^BOOL(id person) { 
    return ([person ID] == 1); 
}] linq_select:^id(id person) { 
    return [person name]; 
}] linq_orderByAscending]; 

NB我删除第二个条件,因为它是没有意义的(ID = 2!)。

目前该库为集合类提供扩展方法(类别),但将来我还会将其功能扩展为NSManagedObjectContext以提供对Core Data的直接查询访问。

相关问题