我不知道是否有可能(以及如何)提供的Objective-C类的东西,如:在Objective-C中是否有类似于LINQ的东西?
Person.Select(@"Name").OrderAsc(@"Name").Where(@"Id").EqualTo(1).And(@"Id").NotEqualTo(2).Load<Array>
这可能是一个项目,我做的非常得心应手。
我喜欢这种编码方式存在于Django & SubSonic。
我不知道是否有可能(以及如何)提供的Objective-C类的东西,如:在Objective-C中是否有类似于LINQ的东西?
Person.Select(@"Name").OrderAsc(@"Name").Where(@"Id").EqualTo(1).And(@"Id").NotEqualTo(2).Load<Array>
这可能是一个项目,我做的非常得心应手。
我喜欢这种编码方式存在于Django & SubSonic。
简短的回答是Objective-C没有Linq的等价物,但是你可以用一个包装类来混合SQLite,NSPredicate和CoreData调用。您可能对core data guide,predicate guide和this 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];
有一个动作比较Windows和Cocoa的做法。可可使用关键路径和NSPredicate ....
我认为,具体到您的例子,这会是可可中的等价物:
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例子更详细和我的一些线条可能已经组合起来了,但在我看来这更容易解析。
查阅以下存储库:https://github.com/ziminji/objective-c-sql-query-builder
这些类提供了一组方便的方法可用于快速构建良好的SQL查询SQLite的。由于它们遵循基本的SQL语法,因此它们使用起来相当简单并且相对简单。
我为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];
我的项目,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的直接查询访问。
我很喜欢Objective-C中的LINQ等价物。有人应该写一个! – 2010-05-11 18:08:42
@JonathanSterling - 我有! https://开头github上。com/ColinEberhardt/LinqToObjectiveC – ColinE 2013-02-15 22:01:38