é åã®ã½ã¼ãï¼
Javaããã°ã©ãã®ããã®Objective-Cã«ãããé åã½ã¼ã解説ã第2å¼¾ã
ååã¯ãNSSortDescriptorã¯ã©ã¹ã使ã£ãé
åã®ã½ã¼ãæ¹æ³ãç´¹ä»ããã
å
容çã«ã¯ã·ã³ãã«ã§ãã£ãã¨ã¯æãããKey-Valueã³ã¼ãã£ã³ã°ããã»ã¬ã¯ã¿ãªã©ãObjective-Cç¬ç¹ã®ææ³ã絡ãã§ããã®ã§ãä»åã¯ãããJavaã«è¿ãæ¸ãæ¹ã§ã½ã¼ãããæ¹æ³ãç´¹ä»ããã
ãã¨ãã°ãããèªç¶ãªé åºä»ããæããªãã¯ã©ã¹ MyClass å ã®ãã£ã¼ã«ã x ã®æé ã«Listãã½ã¼ããããå ´åãJavaã§ã¯ä»¥ä¸ã®ããã«è¨è¿°ã§ããã
public class MyClass { private int x; public MyClass(int x) { this.x = x; } public int x() { return x; } public static void main(String[] args) { java.util.List<MyClass> list = new java.util.ArrayList<>(); list.add(new MyClass(8)); list.add(new MyClass(5)); list.add(new MyClass(4)); list.add(new MyClass(6)); list.add(new MyClass(3)); java.util.Collections.sort(list, new java.util.Comparator<MyClass>() { @Override public int compare(MyClass o1, MyClass o2) { if (o1.x < o2.x) { return -1; } else if (o1.x > o2.x) { return 1; } else { return 0; } } }); for (MyClass o : list) { System.out.println(o.x()); } } }
ããã¨ã»ã¼åããã¨ãObjective-Cã§ããã«ã¯ãjava.util.Comparatorã¤ã³ã¿ã¼ãã§ã¤ã¹ã®ä»£ããã«ãé«éé¢æ°ã使ãã°ããã
以ä¸ã®ããã«å®è£ ã§ããã
@interface MyClass : NSObject @property(assign, nonatomic, readwrite) int x; +(MyClass*)create:(int)x; @end @implementation MyClass @synthesize x; +(MyClass*)create:(int)x { MyClass* ins = [[[MyClass alloc] init] autorelease]; if (ins) { ins.x = x; } return ins; } @end int main(int argc, const char** argv) { @autoreleasepool { NSArray* list = [NSArray arrayWithObjects: [MyClass create:8], [MyClass create:5], [MyClass create:4], [MyClass create:6], [MyClass create:3], nil]; list = [list sortedArrayUsingComparator:^(MyClass* o1, MyClass* o2){ if (o1.x < o2.x) { return (NSComparisonResult)NSOrderedAscending; } else if (o1.x > o2.x) { return (NSComparisonResult)NSOrderedDescending; } else { return (NSComparisonResult)NSOrderedSame; } }]; for (MyClass* o in list) { printf("%d\n", o.x); } } }
Javaã§ç¡åã®Comparatorå®è£
ã¯ã©ã¹ãå®ç¾©ãã¦ããç®æããObjective-Cã®ãããã¯æ§æã«ç½®ãæãããã¦ããã ãã§ãè¨è¿°ãã¦ããå
容ã¯ã»ã¼åãã ã人ã«ãã£ã¦ã¯ãååç´¹ä»ããNSSortDescriptorãããããã¡ãã®æ¹ããããæãã¨ãããã¨ãããã ããã
ã¨ã¯ãããå¤ãã®å ´åãNSSortDescriptorã使ã£ãæ¹ãã¹ãã¼ãã«è¨è¿°ã§ããã¨ã¯æãã
åç´ãª1ããããã£ã®æ¯è¼ã®ã¿ã§ã¯é åºä»ããã§ããªãã¨ãã£ãå ´åã«ã¯ããã¡ãã®Comparatorã使ããã¨ã«ãªãã ããã