001 /*
002 * To change this template, choose Tools | Templates
003 * and open the template in the editor.
004 */
005 package org.bridj.objc;
006
007 import java.util.HashMap;
008 import org.bridj.Pointer;
009 import java.util.Map;
010 import org.bridj.BridJ;
011 import static org.bridj.objc.FoundationLibrary.*;
012 import static org.bridj.Pointer.*;
013
014 /**
015 *
016 * @author ochafik
017 */
018 public class NSDictionary extends NSObject {
019 static {
020 BridJ.register();
021 }
022 public NSDictionary() {
023 super();
024 }
025 // public NSDictionary(Map<String, NSObject> map) {
026 // super(pointerToNSDictionary(map));
027 // }
028
029 public native Pointer<NSObject> valueForKey(Pointer<NSString> key);
030 public native Pointer<NSObject> objectForKey(Pointer<NSObject> key);
031 public native int count();
032
033 public native void getObjects_andKeys(Pointer<Pointer<NSObject>> objects, Pointer<Pointer<NSObject>> keys);
034 public static native Pointer<NSDictionary> dictionaryWithContentsOfFile(Pointer<NSString> path);
035
036 public static native Pointer<NSDictionary> dictionaryWithObjects_forKeys_count(Pointer<Pointer<NSObject>> objects, Pointer<Pointer<NSObject>> keys, int count);
037
038 public static Pointer<NSDictionary> pointerToNSDictionary(Map<String, NSObject> map) {
039 int n = map.size();
040 Pointer<Pointer<NSObject>> objects = allocatePointers(NSObject.class, n);
041 Pointer<Pointer<NSObject>> keys = allocatePointers(NSObject.class, n);
042
043 int i = 0;
044 for (Map.Entry<String, NSObject> e : map.entrySet()) {
045 keys.set(i, (Pointer)pointerToNSString(e.getKey()));
046 objects.set(i, pointerTo(e.getValue()));
047 i++;
048 }
049
050 return dictionaryWithObjects_forKeys_count(objects, keys, n);
051 }
052 public static NSDictionary valueOf(Map<String, NSObject> map) {
053 return pointerToNSDictionary(map).get();
054 }
055 public Map<String, NSObject> toMap() {
056 int n = count();
057 Pointer<Pointer<NSObject>> objects = allocatePointers(NSObject.class, n);
058 Pointer<Pointer<NSString>> keys = allocatePointers(NSString.class, n);
059
060 getObjects_andKeys(objects, (Pointer)keys);
061
062 Map<String, NSObject> ret = new HashMap<String, NSObject>();
063 for (int i = 0; i < n; i++) {
064 Pointer<NSString> key = keys.get(i);
065 Pointer<NSObject> value = objects.get(i);
066
067 ret.put(key.get().toString(), value == null ? null : value.get());
068 }
069 return ret;
070 }
071 }