Source

pyobjc / pyobjc-core / Lib / objc / _convenience.py

The branch 'pyobjc-2.5.x' does not exist.
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
"""
This module implements a callback function that is used by the C code to
add Python special methods to Objective-C classes with a suitable interface.

This module contains no user callable code.

TODO:
- Add external interface: Framework specific modules may want to add to this.

- These are candidates for implementation:

    >>> from Foundation import *
    >>> set(dir(list)) - set(dir(NSMutableArray))
    set(['__delslice__', '__imul__', '__getslice__', '__setslice__',
        '__iadd__', '__mul__', '__add__', '__rmul__'])
    >>> set(dir(dict)) - set(dir(NSMutableDictionary))
    set(['__cmp__'])

"""
from objc._objc import _setClassExtender, selector, lookUpClass, currentBundle, repythonify, splitSignature, _block_call
from objc._objc import registerMetaDataForSelector, _C_NSInteger, _C_ID
import sys
import warnings
import collections

__all__ = ( 'addConvenienceForSelector', 'addConvenienceForClass' )


_CONVENIENCE_METHODS = {}
CLASS_METHODS = {}

if sys.version_info[0] == 2:
    # Use 'xrange' as range to get the same behavior on Python 2 and 3.
    range = xrange


def addConvenienceForSelector(selector, methods):
    """
    Add the list with methods to every class that has a selector with the
    given name.
    """
    warnings.warn("addConvenienceForSelector is on the way out", DeprecationWarning)
    _CONVENIENCE_METHODS[selector] = methods

def addConvenienceForClass(classname, methods):
    """
    Add the list with methods to the class with the specified name
    """
    CLASS_METHODS[classname] = methods

NSObject = lookUpClass('NSObject')

def add_convenience_methods(super_class, name, type_dict):
    """
    Add additional methods to the type-dict of subclass 'name' of
    'super_class'.

    _CONVENIENCE_METHODS is a global variable containing a mapping from
    an Objective-C selector to a Python method name and implementation.

    CLASS_METHODS is a global variable containing a mapping from
    class name to a list of Python method names and implementation.

    Matching entries from both mappings are added to the 'type_dict'.
    """
    if type_dict.get('__objc_python_subclass__'):
        if 'bundleForClass' not in type_dict:
            cb = currentBundle()
            def bundleForClass(cls):
                return cb
            type_dict['bundleForClass'] = selector(bundleForClass, isClassMethod=True)

    look_at_super = (super_class is not None and super_class.__name__ != 'Object')

    for k, sel in list(type_dict.items()):
        if not isinstance(sel, selector):
            continue

        #
        # Handle some common exceptions to the usual rules:
        #

        sel = sel.selector

        if sel in _CONVENIENCE_METHODS:
            v = _CONVENIENCE_METHODS[sel]
            for nm, value in v:
                if nm in type_dict and isinstance(type_dict[nm], selector):

                    # Clone attributes of already existing version

                    t = type_dict[nm]
                    v = selector(value, selector=t.selector,
                        signature=t.signature, isClassMethod=t.isClassMethod)

                    type_dict[nm] = v

                elif look_at_super and hasattr(super_class, nm):
                    # Skip, inherit the implementation from a super_class
                    pass

                elif nm not in type_dict:
                    type_dict[nm] = value

    if name in CLASS_METHODS:
        for nm, value in CLASS_METHODS[name]:
            type_dict[nm] = value


    if name == 'NSObject':
        class kvc (object):
            """
            Key-Value-Coding accessor for Cocoa objects.

            Both attribute access and dict-like indexing will attempt to
            access the requested item through Key-Value-Coding.
            """
            __slots__ = ('__object',)
            def __init__(self, value):
                self.__object = value

            def __repr__(self):
                return "<KVC accessor for %r>"%(self.__object,)

            def __getattr__(self, key):
                try:
                    return self.__object.valueForKey_(key)
                except KeyError as msg:
                    if hasattr(msg, '_pyobjc_info_') and msg._pyobjc_info_['name'] == 'NSUnknownKeyException':
                        raise AttributeError(key)

                    raise
            def __setattr__(self, key, value):
                if not key.startswith('_'):
                    return self.__object.setValue_forKey_(value, key)
                else:
                    super(kvc, self).__setattr__(key, value)

            def __getitem__(self, key):
                if not isinstance(key, STR_TYPES):
                    raise TypeError("Key must be string")
                return self.__object.valueForKey_(key)

            def __setitem__(self, key, value):
                if not isinstance(key, STR_TYPES):
                    raise TypeError("Key must be string")
                return self.__object.setValue_forKey_(value, key)

        type_dict['_'] = property(kvc)

_setClassExtender(add_convenience_methods)


#
# The following conveniences should strictly speaking be in
# in pyobjc-framework-Foundation, but as they are very fundamental
# we're keeping them here.
#

def __getitem__objectForKey_(self, key):
    res = self.objectForKey_(container_wrap(key))
    return container_unwrap(res, KeyError, key)

def has_key_objectForKey_(self, key):
    res = self.objectForKey_(container_wrap(key))
    return res is not None

def get_objectForKey_(self, key, dflt=None):
    res = self.objectForKey_(container_wrap(key))
    if res is None:
        res = dflt
    return res

_CONVENIENCE_METHODS[b'objectForKey:'] = (
    ('__getitem__', __getitem__objectForKey_),
    ('get', get_objectForKey_),
    ('__contains__', has_key_objectForKey_),
)
if sys.version_info[0] == 2:
    _CONVENIENCE_METHODS[b'objectForKey:'] += (
        ('has_key', has_key_objectForKey_),
    )




def __delitem__removeObjectForKey_(self, key):
    self.removeObjectForKey_(container_wrap(key))

_CONVENIENCE_METHODS[b'removeObjectForKey:'] = (
    ('__delitem__', __delitem__removeObjectForKey_),
)

def update_setObject_forKey_(self, *args, **kwds):
    # XXX - should this be more flexible?
    if len(args) == 0:
        pass
    elif len(args) != 1:
        raise TypeError("update expected at most 1 arguments, got {0}".format(
            len(args)))


    else:
        other = args[0]
        if hasattr(other, 'keys'):
            # This mirrors the implementation of dict.update, but seems
            # wrong for Python3 (with collectons.Dict)
            for key in other.keys():
                self[key] = other[key]

        else:
            for key, value in other:
                self[key] = value

    for k in kwds:
        self[k] = kwds[k]

def setdefault_setObject_forKey_(self, key, dflt=None):
    try:
        return self[key]
    except KeyError:
        self[key] = dflt
        return dflt

def __setitem__setObject_forKey_(self, key, value):
    self.setObject_forKey_(container_wrap(value), container_wrap(key))

pop_setObject_dflt=object()
def pop_setObject_forKey_(self, key, dflt=pop_setObject_dflt):
    try:
        res = self[key]
    except KeyError:
        if dflt == pop_setObject_dflt:
            raise KeyError(key)
        res = dflt
    else:
        del self[key]
    return res

NSAutoreleasePool = lookUpClass('NSAutoreleasePool')

def popitem_setObject_forKey_(self):
    try:
        it = self.keyEnumerator()
        k = container_unwrap(it.nextObject(), StopIteration)
    except (StopIteration, IndexError):
        raise KeyError("popitem on an empty %s" % (type(self).__name__,))
    else:
        result = (k, container_unwrap(self.objectForKey_(k), KeyError))
        self.removeObjectForKey_(k)
        return result

_CONVENIENCE_METHODS[b'setObject:forKey:'] = (
    ('__setitem__', __setitem__setObject_forKey_),
    ('update', update_setObject_forKey_),
    ('setdefault', setdefault_setObject_forKey_),
    ('pop', pop_setObject_forKey_),
    ('popitem', popitem_setObject_forKey_),
)


_CONVENIENCE_METHODS[b'count'] = (
    ('__len__', lambda self: self.count()),
)

def containsObject_has_key(self, elem):
    return bool(self.containsObject_(container_wrap(elem)))

_CONVENIENCE_METHODS[b'containsObject:'] = (
    ('__contains__', containsObject_has_key),
)



def nsobject_hash(self, _max=sys.maxsize, _const=((sys.maxsize + 1) * 2)):
    rval = self.hash()
    if rval > _max:
        rval -= _const
        # -1 is not a valid hash in Python and hash(x) will
        # translate a hash of -1 to -2, so we might as well
        # do it here so that it's not too surprising..
        if rval == -1:
            rval = -2
    return int(rval)

def nsobject__eq__(self, other):
    return bool(self.isEqualTo_(other))

def nsobject__ne__(self, other):
    return bool(self.isNotEqualTo_(other))

def nsobject__gt__(self, other):
    return bool(self.isGreaterThan_(other))

def nsobject__ge__(self, other):
    return bool(self.isGreaterThanOrEqualTo_(other))

def nsobject__lt__(self, other):
    return bool(self.isLessThan_(other))

def nsobject__le__(self, other):
    return bool(self.isLessThanOrEqualTo_(other))

CLASS_METHODS["NSObject"] = (
    ('__hash__', nsobject_hash),
    ('__eq__', nsobject__eq__),
    ('__ne__', nsobject__ne__),
    ('__gt__', nsobject__gt__),
    ('__ge__', nsobject__ge__),
    ('__lt__', nsobject__lt__),
    ('__le__', nsobject__le__),
)

if sys.version_info[0] == 2:
    def nsobject__cmp__(self, other):
        try:
            func = self.compare_

        except AttributeError:
            return NotImplemented
            if self < other:
                return -1
            elif self > other:
                return 1
            else:
                return 0

        else:
            return func(other)

    CLASS_METHODS["NSObject"] += (
        ("__cmp__", nsobject__cmp__),
    )




_CONVENIENCE_METHODS[b'length'] = (
    ('__len__', lambda self: self.length()),
)

_CONVENIENCE_METHODS[b'addObject:'] = (
    ('append', lambda self, item: self.addObject_(container_wrap(item))),
)

def reverse_exchangeObjectAtIndex_withObjectAtIndex_(self):
    begin = 0
    end = len(self) - 1
    while begin < end:
        self.exchangeObjectAtIndex_withObjectAtIndex_(begin, end)
        begin += 1
        end -= 1

_CONVENIENCE_METHODS[b'exchangeObjectAtIndex:withObjectAtIndex:'] = (
    ('reverse', reverse_exchangeObjectAtIndex_withObjectAtIndex_),
)

def ensureArray(anArray):
    if not isinstance(anArray, (NSArray, list, tuple)):
        anArray = list(anArray)
    return anArray


def extend_addObjectsFromArray_(self, anArray):
    self.addObjectsFromArray_(ensureArray(anArray))

_CONVENIENCE_METHODS[b'addObjectsFromArray:'] = (
    ('extend', extend_addObjectsFromArray_),
)

_index_sentinel=object()
def index_indexOfObject_inRange_(self, item, start=0, stop=_index_sentinel):
    #from Foundation import NSNotFound
    NSNotFound = sys.maxsize
    if start == 0 and stop is _index_sentinel:
        res = self.indexOfObject_(container_wrap(item))
        if res == NSNotFound:
            raise ValueError("%s.index(x): x not in list" % (type(self).__name__,))
    else:
        l = len(self)
        if start < 0:
            start = l + start
            if start < 0:
                start = 0

        if stop is not _index_sentinel:
            if stop < 0:
                stop = l + stop
                if stop < 0:
                    stop = 0
        else:
            stop = l

        itemcount = len(self)

        if itemcount == 0:
            raise ValueError("%s.index(x): x not in list" % (type(self).__name__,))

        else:
            if start >= itemcount:
                start = itemcount - 1
            if stop >= itemcount:
                stop = itemcount - 1

            if stop <= start:
                ln = 0
            else:

                ln = stop - start


            if ln == 0:
                raise ValueError("%s.index(x): x not in list" % (type(self).__name__,))

            if ln > sys.maxsize:
                ln = sys.maxsize

            res = self.indexOfObject_inRange_(item, (start, ln))
            if res == NSNotFound:
                raise ValueError("%s.index(x): x not in list" % (type(self).__name__,))
    return res

_CONVENIENCE_METHODS[b'indexOfObject:inRange:'] = (
    ('index', index_indexOfObject_inRange_),
)

def insert_insertObject_atIndex_(self, idx, item):
    if idx < 0:
        idx += len(self)
        if idx < 0:
            raise IndexError("list index out of range")
    self.insertObject_atIndex_(container_wrap(item), idx)

_CONVENIENCE_METHODS[b'insertObject:atIndex:'] = (
    ( 'insert', insert_insertObject_atIndex_),
)

if sys.version_info[0] == 2:
    INT_TYPES = (int, long)

else:
    INT_TYPES = int

def __getitem__objectAtIndex_(self, idx):
    if isinstance(idx, slice):
        start, stop, step = idx.indices(len(self))
        #if step == 1:
        #    m = getattr(self, 'subarrayWithRange_', None)
        #    if m is not None:
        #        return m((start, stop - start))
        return [self[i] for i in range(start, stop, step)]

    elif not isinstance(idx, INT_TYPES):
        raise TypeError("index must be a number")

    if idx < 0:
        idx += len(self)
        if idx < 0:
            raise IndexError("list index out of range")

    return container_unwrap(self.objectAtIndex_(idx), RuntimeError)

def __getslice__objectAtIndex_(self, i, j):
    i = max(i, 0); j = max(j, 0)
    return __getitem__objectAtIndex_(self, slice(i, j))

_CONVENIENCE_METHODS[b'objectAtIndex:'] = (
    ('__getitem__', __getitem__objectAtIndex_),
    ('__getslice__', __getslice__objectAtIndex_),
)

def __delitem__removeObjectAtIndex_(self, idx):
    if isinstance(idx, slice):
        start, stop, step = idx.indices(len(self))
        if step == 1:
            if start > stop:
                start, stop = stop, start
            m = getattr(self, 'removeObjectsInRange_', None)
            if m is not None:
                m((start, stop - start))
                return
        r = reversed(range(start, stop, step))
        for i in r:
            self.removeObjectAtIndex_(i)
        return
    if idx < 0:
        idx += len(self)
        if idx < 0:
            raise IndexError("list index out of range")

    self.removeObjectAtIndex_(idx)

def __delslice__removeObjectAtIndex_(self, i, j):
    __delitem__removeObjectAtIndex_(self, slice(i, j))

def pop_removeObjectAtIndex_(self, idx=-1):
    length = len(self)
    if length <= 0:
        raise IndexError("pop from empty list")
    elif idx >= length or (idx + length) < 0:
        raise IndexError("pop index out of range")
    elif idx < 0:
        idx += len(self)
        if idx < 0:
            raise IndexError("list index out of range")
    rval = self[idx]
    self.removeObjectAtIndex_(idx)
    return rval

def remove_removeObjectAtIndex_(self, obj):
    idx = self.index(obj)
    self.removeObjectAtIndex_(idx)

_CONVENIENCE_METHODS[b'removeObjectAtIndex:'] = (
    ('remove', remove_removeObjectAtIndex_),
    ('pop', pop_removeObjectAtIndex_),
    ('__delitem__', __delitem__removeObjectAtIndex_),
    ('__delslice__', __delslice__removeObjectAtIndex_),
)

def __setitem__replaceObjectAtIndex_withObject_(self, idx, anObject):
    if isinstance(idx, slice):
        start, stop, step = idx.indices(len(self))
        if step >=0:
            if stop <= start:
                # Empty slice: insert values
                stop = start
        elif start <= stop:
            start = stop

        if step == 1:
            m = getattr(self, 'replaceObjectsInRange_withObjectsFromArray_', None)
            if m is not None:
                m((start, stop - start), ensureArray(anObject))
                return

        if not isinstance(anObject, (NSArray, list, tuple)):
            anObject = list(anObject)

        slice_len = len(range(start, stop, step))
        if slice_len != len(anObject):
            raise ValueError("Replacing extended slice with %d elements by %d elements"%(
                slice_len, len(anObject)))

        if step > 0:
            if anObject is self:
                toAssign = list(anObject)
            else:
                toAssign = anObject
            for inIdx, outIdx in enumerate(range(start, stop, step)):
                self.replaceObjectAtIndex_withObject_(outIdx, toAssign[inIdx])

        elif step == 0:
            raise ValueError("Step 0")

        else:
            if anObject is self:
                toAssign = list(anObject)
            else:
                toAssign = anObject
            for inIdx, outIdx in enumerate(range(start, stop, step)):
                self.replaceObjectAtIndex_withObject_(outIdx, toAssign[inIdx])


    elif not isinstance(idx, INT_TYPES):
        raise TypeError("index is not an integer")

    else:

        if idx < 0:
            idx += len(self)
            if idx < 0:
                raise IndexError("list index out of range")

        self.replaceObjectAtIndex_withObject_(idx, anObject)

def __setslice__replaceObjectAtIndex_withObject_(self, i, j, seq):
    i = max(i, 0)
    j = max(j, 0)
    __setitem__replaceObjectAtIndex_withObject_(self, slice(i, j), seq)

_CONVENIENCE_METHODS[b'replaceObjectAtIndex:withObject:'] = (
    ('__setitem__', __setitem__replaceObjectAtIndex_withObject_),
    ('__setslice__', __setslice__replaceObjectAtIndex_withObject_),
)

def enumeratorGenerator(anEnumerator):
    while True:
        yield container_unwrap(anEnumerator.nextObject(), StopIteration)

def dictItems(aDict):
    """
    NSDictionary.items()
    """
    keys = aDict.allKeys()
    return zip(keys, map(aDict.__getitem__, keys))

def itemsGenerator(aDict):
    for key in aDict:
        yield (key, aDict[key])

def __iter__objectEnumerator_keyEnumerator(self):
    meth = getattr(self, 'keyEnumerator', None)
    if meth is None:
        meth = self.objectEnumerator
    return iter(meth())

_CONVENIENCE_METHODS[b'keyEnumerator'] = (
    ('__iter__', __iter__objectEnumerator_keyEnumerator),
)
if sys.version_info[0] == 2:
    _CONVENIENCE_METHODS[b'keyEnumerator'] += (
        ('iterkeys', lambda self: iter(self.keyEnumerator())),
        ('iteritems', lambda self: itemsGenerator(self)),
)

_CONVENIENCE_METHODS[b'objectEnumerator'] = (
    ('__iter__', __iter__objectEnumerator_keyEnumerator),
)

if sys.version_info[0] == 2:
    _CONVENIENCE_METHODS[b'objectEnumerator'] += (
        ('itervalues', lambda self: iter(self.objectEnumerator())),
    )

_CONVENIENCE_METHODS[b'reverseObjectEnumerator'] = (
    ('__reversed__', lambda self: iter(self.reverseObjectEnumerator())),
)

_CONVENIENCE_METHODS[b'removeAllObjects'] = (
    ('clear', lambda self: self.removeAllObjects()),
)

_CONVENIENCE_METHODS[b'dictionaryWithDictionary:'] = (
    ('copy', lambda self: type(self).dictionaryWithDictionary_(self)),
)

_CONVENIENCE_METHODS[b'nextObject'] = (
    ('__iter__', enumeratorGenerator),
)

#
# NSNumber seems to be and abstract base-class that is implemented using
# NSCFNumber, a CoreFoundation 'proxy'.
#
NSNull = lookUpClass('NSNull')
NSArray = lookUpClass('NSArray')
#null = NSNull.null()

number_wrap = repythonify

def container_wrap(v):
    if v is None:
        return NSNull.null()
    return v

def container_unwrap(v, exc_type, *exc_args):
    if v is None:
        raise exc_type(*exc_args)
    elif v is NSNull.null():
        return None
    return v


def fromkeys_dictionaryWithObjects_forKeys_(cls, keys, values=None):
    if not isinstance(keys, (list, tuple)):
        keys = list(keys)
    if values is None:
        values = (None,) * len(keys)
    elif not isinstance(values, (list, tuple)):
        values = list(values)
    return cls.dictionaryWithObjects_forKeys_(values, keys)

if sys.version_info[0] == 3:
    def cmp(a, b):
        if a == b:
            return 0
        elif a < b:
            return -1
        else:
            return 1

def sort(self, key=None, reverse=False, cmpfunc=cmp):
    # NOTE: cmpfunc argument is for backward compatibility.
    if key is None:
        if reverse:
            def doCmp(a, b, cmpfunc):
                return -cmpfunc(a, b)
        else:
            def doCmp(a, b, cmpfunc):
                return cmpfunc(a, b)
    else:
        # This is (a lot) slower than the algoritm used for
        # list.sort, but so be it.
        if reverse:
            def doCmp(a, b, cmpfunc):
                return -cmpfunc(key(a), key(b))
        else:
            def doCmp(a, b, cmpfunc):
                return cmpfunc(key(a), key(b))

    self.sortUsingFunction_context_(doCmp, cmpfunc)


registerMetaDataForSelector(b"NSObject", b"sortUsingFunction:context:",
        dict(
            arguments={
                2:  {
                        'callable': {
                            'reval': { 'type': _C_NSInteger },
                            'arguments': {
                                0: { 'type': _C_ID },
                                1: { 'type': _C_ID },
                                2: { 'type': _C_ID },
                            }
                        },
                        'callable_retained': False,
                },
                3:  { 'type': _C_ID },
            },
        ))


_CONVENIENCE_METHODS[b'sortUsingFunction:context:'] = (
    ('sort', sort),
)

_CONVENIENCE_METHODS[b'hasPrefix:'] = (
    ('startswith', lambda self, pfx: self.hasPrefix_(pfx)),
)

_CONVENIENCE_METHODS[b'hasSuffix:'] = (
    ('endswith', lambda self, pfx: self.hasSuffix_(pfx)),
)


def __copy__(self):
    if hasattr(self, 'mutableCopy'):
        return self.mutableCopyWithZone_(None)
    return self.copyWithZone_(None)
_CONVENIENCE_METHODS[b'copyWithZone:'] = (
    ('__copy__', __copy__),
)

# This won't work:
#NSKeyedArchiver = lookUpClass('NSKeyedArchiver')
#NSKeyedUnarchiver = lookUpClass('NSKeyedUnarchiver')
#def coder_deepcopy(self, memo):
#   buf = NSKeyedArchiver.archivedDataWithRootObject_(self)
#   result = NSKeyedUnarchiver.unarchiveObjectWithData_(buf)
#   return result
#
#_CONVENIENCE_METHODS['encodeWithCoder:'] = (
#   ('__deepcopy__', coder_deepcopy ),
#)

CLASS_METHODS['NSNull'] = (
    ('__nonzero__',  lambda self: False ),
    ('__bool__',  lambda self: False ),
)

NSDecimalNumber = lookUpClass('NSDecimalNumber')
def _makeD(v):
    if isinstance(v, NSDecimalNumber):
        return v

    return NSDecimalNumber.decimalNumberWithDecimal_(v)

def decimal__add__(self, other):
    return _makeD(self.decimalValue() + other)

def decimal__radd__(self, other):
    return _makeD(other + self.decimalValue())

CLASS_METHODS['NSDecimalNumber'] = (
    ('__add__', decimal__add__),
    ('__radd__', decimal__radd__),
    ('__sub__', lambda self, other: _makeD(self.decimalValue() - other)),
    ('__rsub__', lambda self, other: _makeD(other - self.decimalValue())),
    ('__mul__', lambda self, other: _makeD(self.decimalValue() * other)),
    ('__rmul__', lambda self, other: _makeD(other * self.decimalValue())),
    ('__div__', lambda self, other: _makeD(self.decimalValue() / other)),
    ('__rdiv__', lambda self, other: _makeD(other / self.decimalValue())),
    ('__truediv__', lambda self, other: _makeD(self.decimalValue() / other)),
    ('__rtruediv__', lambda self, other: _makeD(other / self.decimalValue())),
    ('__floordiv__', lambda self, other: _makeD(self.decimalValue() // other)),
    ('__rfloordiv__', lambda self, other: _makeD(other // self.decimalValue())),
    ('__mod__', lambda self, other: _makeD(self.decimalValue() % other)),
    ('__rmod__', lambda self, other: _makeD(other % self.decimalValue())),
    ('__neg__', lambda self: _makeD(-(self.decimalValue()))),
    ('__pos__', lambda self: _makeD(+(self.decimalValue()))),
    ('__abs__', lambda self: _makeD(abs(self.decimalValue()))),
    ('__round__', lambda self, n=0 : _makeD(round(self.decimalValue(), n))),
)

def NSData__getslice__(self, i, j):
    return self.bytes()[i:j]

def NSData__getitem__(self, item):
    buff = self.bytes()
    try:
        return buff[item]
    except TypeError:
        return buff[:][item]


if sys.version_info[:2] <= (2,6):
    def NSData__str__(self):
        return self.bytes()[:]

elif sys.version_info[0] == 2:
    def NSData__str__(self):
        return str(self.bytes().tobytes())

else:
    def NSData__str__(self):
        return str(self.bytes().tobytes())


CLASS_METHODS['NSData'] = (
    ('__str__', NSData__str__),
    ('__getitem__', NSData__getitem__),
    ('__getslice__', NSData__getslice__),
)

def NSMutableData__setslice__(self, i, j, sequence):
    # XXX - could use replaceBytes:inRange:, etc.
    self.mutableBytes()[i:j] = sequence

def NSMutableData__setitem__(self, item, value):
    self.mutableBytes()[item] = value

CLASS_METHODS['NSMutableData'] = (
    ('__setslice__', NSMutableData__setslice__),
    ('__setitem__', NSMutableData__setitem__),
)


def __call__(self, *args, **kwds):
    return _block_call(self, self.__block_signature__, args, kwds)

CLASS_METHODS['NSBlock'] = (
    ('__call__', __call__),
)


if sys.version_info[0] == 3 or (sys.version_info[0] == 2 and sys.version_info[1] >= 6):

    def all_contained_in(inner, outer):
        """
        Return True iff all items in ``inner`` are also in ``outer``.
        """
        for v in inner:
            if v not in outer:
                return False

        return True

    class nsdict_view (collections.Set):
        __slots__ = ()

        def __eq__(self, other):
            if not isinstance(other, collections.Set):
                return NotImplemented

            if len(self) == len(other):
                return all_contained_in(self, other)

            else:
                return False

        def __ne__(self, other):
            if not isinstance(other, collections.Set):
                return NotImplemented

            if len(self) == len(other):
                return not all_contained_in(self, other)

            else:
                return True

        def __lt__(self, other):
            if not isinstance(other, collections.Set):
                return NotImplemented

            if len(self) < len(other):
                return all_contained_in(self, other)

            else:
                return False

        def __le__(self, other):
            if not isinstance(other, collections.Set):
                return NotImplemented

            if len(self) <= len(other):
                return all_contained_in(self, other)

            else:
                return False

        def __gt__(self, other):
            if not isinstance(other, collections.Set):
                return NotImplemented

            if len(self) > len(other):
                return all_contained_in(other, self)

            else:
                return False

        def __ge__(self, other):
            if not isinstance(other, collections.Set):
                return NotImplemented

            if len(self) >= len(other):
                return all_contained_in(other, self)

            else:
                return False

        def __and__(self, other):
            if not isinstance(other, collections.Set):
                return NotImplemented
            result = set(self)
            result.intersection_update(other)
            return result

        def __or__(self, other):
            if not isinstance(other, collections.Set):
                return NotImplemented
            result = set(self)
            result.update(other)
            return result

        def __ror__(self, other):
            if not isinstance(other, collections.Set):
                return NotImplemented
            result = set(self)
            result.update(other)
            return result

        def __sub__(self, other):
            if not isinstance(other, collections.Set):
                return NotImplemented
            result = set(self)
            result.difference_update(other)
            return result

        def __xor__(self, other):
            if not isinstance(other, collections.Set):
                return NotImplemented
            result = set(self)
            result.symmetric_difference_update(other)
            return result

    #collections.Set.register(nsdict_view)

    class nsdict_keys(nsdict_view):
        __slots__=('__value')
        def __init__(self, value):
            self.__value =  value

        def __repr__(self):
            keys = list(self.__value)
            #keys.sort()

            return "<nsdict_keys({0})>".format(keys)


        def __len__(self):
            return len(self.__value)

        def __iter__(self):
            return iter(self.__value)

        def __contains__(self, value):
            return value in self.__value

    class nsdict_values(nsdict_view):
        __slots__=('__value')
        def __init__(self, value):
            self.__value =  value

        def __repr__(self):
            values = list(self)
            values.sort()

            return "<nsdict_values({0})>".format(values)

        def __len__(self):
            return len(self.__value)

        def __iter__(self):
            return iter(self.__value.objectEnumerator())

        def __contains__(self, value):
            for v in iter(self):
                if value == v:
                    return True
            return False

    class nsdict_items(nsdict_view):

        __slots__=('__value')

        def __init__(self, value):
            self.__value =  value

        def __repr__(self):
            values = list(self)
            values.sort()

            return "<nsdict_items({0})>".format(values)

        def __len__(self):
            return len(self.__value)

        def __iter__(self):
            for k in self.__value:
                yield (k, self.__value[k])

        def __contains__(self, value):
            for v in iter(self):
                if value == v:
                    return True
            return False

    collections.KeysView.register(nsdict_keys)
    collections.ValuesView.register(nsdict_values)
    collections.ItemsView.register(nsdict_items)

    collections.Mapping.register(lookUpClass('NSDictionary'))
    collections.MutableMapping.register(lookUpClass('NSMutableDictionary'))



    NSDictionary = lookUpClass('NSDictionary')
    def nsdict_fromkeys(cls, keys, value=None):
        keys = [container_wrap(k) for k in keys]
        values = [container_wrap(value)]*len(keys)

        return NSDictionary.dictionaryWithObjects_forKeys_(values, keys)

    NSMutableDictionary = lookUpClass('NSMutableDictionary')
    def nsmutabledict_fromkeys(cls, keys, value=None):
        result = NSMutableDictionary.dictionary()
        value = container_wrap(value)
        for k in keys:
            result[container_wrap(k)] = value

        return result

    def dict_new(cls, args, kwds):
        if len(args) == 0:
            pass

        elif len(args) == 1:
            d = dict()
            if isinstance(args[0], collections.Mapping):
                items = args[0].items()
            else:
                items = args[0]
            for k , v in items:
                d[container_wrap(k)] = container_wrap(v)

            for k, v in kwds.items():
                d[container_wrap(k)] = container_wrap(v)

            return cls.dictionaryWithDictionary_(d)

        else:
            raise TypeError(
                    "dict expected at most 1 arguments, got {0}".format(
                        len(args)))
        if kwds:
            d = dict()
            for k, v in kwds.items():
                d[container_wrap(k)] = container_wrap(v)

            return cls.dictionaryWithDictionary_(d)

        return cls.dictionary()

    def nsdict_new(cls, *args, **kwds):
        return dict_new(NSDictionary, args, kwds)

    def nsmutabledict_new(cls, *args, **kwds):
        return dict_new(NSMutableDictionary, args, kwds)


    def nsdict__eq__(self, other):
        if not isinstance(other, collections.Mapping):
            return False

        return self.isEqualToDictionary_(other)

    def nsdict__ne__(self, other):
        return not nsdict__eq__(self, other)

    def nsdict__richcmp__(self, other):
        return NotImplemented


    if sys.version_info[0] == 3:
        CLASS_METHODS['NSDictionary'] = (
            ('fromkeys', classmethod(nsdict_fromkeys)),
            ('keys', lambda self: nsdict_keys(self)),
            ('values', lambda self: nsdict_values(self)),
            ('items', lambda self: nsdict_items(self)),

            # Explicitly add these methods, instead of relying
            # on the selector based selection.
            #
            # Primary reason: turns out at least the chosen
            # implementation for __contains__ depends on dict
            # iteration order, and one of the implementation doesn't
            # work for NSDictionary.
            #
            # In the slightly longer run all python API
            # implementations will be added explictly to
            # classes because of this, and because this allows
            # for a faster implementation of method dispatch.
            ('__getitem__', __getitem__objectForKey_),
            ('get', get_objectForKey_),
            ('__contains__', has_key_objectForKey_),
        )

        CLASS_METHODS['NSMutableDictionary'] = (
            ('fromkeys', classmethod(nsmutabledict_fromkeys)),
        )

    else:
        CLASS_METHODS['NSDictionary'] = (
            ('fromkeys', classmethod(nsdict_fromkeys)),
            ('viewkeys', lambda self: nsdict_keys(self)),
            ('viewvalues', lambda self: nsdict_values(self)),
            ('viewitems', lambda self: nsdict_items(self)),
            ('keys', lambda self: self.allKeys()),
            ('items', lambda self: dictItems(self)),
            ('values', lambda self: self.allValues()),
            ('__getitem__', __getitem__objectForKey_),
            ('get', get_objectForKey_),
            ('__contains__', has_key_objectForKey_),
            ('has_key', has_key_objectForKey_),
        )

    CLASS_METHODS['NSDictionary'] += (
        ('__eq__', nsdict__eq__),
        ('__ne__', nsdict__ne__),
        ('__lt__', nsdict__richcmp__),
        ('__le__', nsdict__richcmp__),
        ('__gt__', nsdict__richcmp__),
        ('__ge__', nsdict__richcmp__),
    )

    NSDictionary.__new__ = nsdict_new
    NSMutableDictionary.__new__ = nsmutabledict_new

    NSMutableDictionary.dictionary()

    #FIXME: This shouldn't be necessary

NSMutableArray = lookUpClass('NSMutableArray')
def nsarray_add(self, other):
    result = NSMutableArray.arrayWithArray_(self)
    result.extend(other)
    return result

def nsarray_radd(self, other):
    result = NSMutableArray.arrayWithArray_(other)
    result.extend(self)
    return result

def nsarray_mul(self, other):
    """
    This tries to implement anNSArray * N
    somewhat efficently (and definitely more
    efficient that repeated appending).
    """
    result = NSMutableArray.array()

    if other <= 0:
        return result

    n = 1
    tmp = self
    while other:
        if other & n != 0:
            result.extend(tmp)
            other -= n

        if other:
            n <<= 1
            tmp = tmp.arrayByAddingObjectsFromArray_(tmp)

    return result



def nsarray_new(cls, sequence=None):
    if not sequence:
        return NSArray.array()

    elif isinstance(sequence, STR_TYPES):
        return NSArray.arrayWithArray_(list(sequence))

    else:
        if not isinstance(sequence, (list, tuple)):
            # FIXME: teach bridge to treat range and other list-lik
            # types correctly
            return NSArray.arrayWithArray_(list(sequence))

        return NSArray.arrayWithArray_(sequence)

if sys.version_info[0] == 2:
    STR_TYPES=(str, unicode)
else:
    STR_TYPES=str

def nsmutablearray_new(cls, sequence=None):
    if not sequence:
        return NSMutableArray.array()

    elif isinstance(sequence, STR_TYPES):
        return NSMutableArray.arrayWithArray_(list(sequence))

    else:
        if not isinstance(sequence, (list, tuple)):
            # FIXME: teach bridge to treat range and other list-lik
            # types correctly
            return NSMutableArray.arrayWithArray_(list(sequence))

        return NSMutableArray.arrayWithArray_(sequence)

CLASS_METHODS['NSArray'] = (
    ('__add__', nsarray_add),
    ('__radd__', nsarray_radd),
    ('__mul__', nsarray_mul),
    ('__rmul__', nsarray_mul),
)

# Force scans to ensure __new__ is set correctly
# FIXME: This shouldn't be necessary!
NSArray.__new__ = nsarray_new
NSMutableArray.__new__ = nsmutablearray_new
NSMutableArray.alloc().init()
#NSMutableSet.set()

NSSet = lookUpClass('NSSet')
NSMutableSet = lookUpClass('NSMutableSet')

try:
    from collections import Set
    Set.register(NSSet)
except:
    Set = (set, frozenset, NSSet)

def nsset_isdisjoint(self, other):
    for item in self:
        if item in other:
            return False
    return True

def nsset_union(self, *other):
    result = NSMutableSet()
    result.unionSet_(self)
    for val in other:
        if isinstance(val, Set):
            result.unionSet_(val)
        else:
            result.unionSet_(set(val))
    return result

def nsset_intersection(self, *others):
    if len(others) == 0:
        return self.mutableCopy()
    result = NSMutableSet()
    for item in self:
        for o in others:
            if item not in o:
                break
        else:
            result.add(item)
    return result

def nsset_difference(self, *others):
    result = self.mutableCopy()

    for value in others:
        if isinstance(value, Set):
            result.minusSet_(value)
        else:
            result.minusSet_(set(value))

    return result

def nsset_symmetric_difference(self, other):
    result = NSMutableSet()
    for item in self:
        if item not in other:
            result.add(item)
    for item in other:
        if item not in self:
            result.add(item)
    return result


def nsset__contains__(self, value):
    hash(value) # Force error for non-hashable values
    return self.containsObject_(value)

def nsset__or__(self, other):
    if not isinstance(self, Set):
        raise TypeError("NSSet|value where value is not a set")
    if not isinstance(other, Set):
        raise TypeError("NSSet|value where value is not a set")
    return nsset_union(self, other)

def nsset__ror__(self, other):
    if not isinstance(self, Set):
        raise TypeError("value|NSSet where value is not a set")
    if not isinstance(other, Set):
        raise TypeError("value|NSSet where value is not a set")
    return nsset_union(other, self)

def nsset__and__(self, other):
    if not isinstance(self, Set):
        raise TypeError("NSSet&value where value is not a set")
    if not isinstance(other, Set):
        raise TypeError("NSSet&value where value is not a set")
    return nsset_intersection(self, other)

def nsset__rand__(self, other):
    if not isinstance(self, Set):
        raise TypeError("value&NSSet where value is not a set")
    if not isinstance(other, Set):
        raise TypeError("value&NSSet where value is not a set")
    return nsset_intersection(other, self)

def nsset__sub__(self, other):
    if not isinstance(self, Set):
        raise TypeError("NSSet-value where value is not a set")
    if not isinstance(other, Set):
        raise TypeError("NSSet-value where value is not a set")
    return nsset_difference(self, other)

def nsset_rsub__(self, other):
    if not isinstance(self, Set):
        raise TypeError("NSSet-value where value is not a set")
    if not isinstance(other, Set):
        raise TypeError("NSSet-value where value is not a set")
    return nsset_difference(other, self)

def nsset__xor__(self, other):
    if not isinstance(self, Set):
        raise TypeError("NSSet-value where value is not a set")
    if not isinstance(other, Set):
        raise TypeError("NSSet-value where value is not a set")
    return nsset_symmetric_difference(other, self)

def nsset_issubset(self, other):
    if isinstance(other, Set):
        return self.isSubsetOfSet_(other)

    else:
        return self.isSubsetOfSet_(set(other))

def nsset__le__(self, other):
    if not isinstance(other, Set):
        raise TypeError()
    return nsset_issubset(self, other)

def nsset__eq__(self, other):
    if not isinstance(other, Set):
        return False

    return self.isEqualToSet_(other)

def nsset__ne__(self, other):
    if not isinstance(other, Set):
        return True

    return not self.isEqualToSet_(other)

def nsset__lt__(self, other):
    if not isinstance(other, Set):
        raise TypeError()

    return (self <= other) and (self != other)

def nsset_issuperset(self, other):
    if not isinstance(other, Set):
        other = set(other)

    for item in other:
        if item not in self:
            return False

    return True

def nsset__ge__(self, other):
    if not isinstance(other, Set):
        raise TypeError()
    return nsset_issuperset(self, other)

def nsset__gt__(self, other):
    if not isinstance(other, Set):
        raise TypeError()
    return (self >= other) and (self != other)

if sys.version_info[0] == 2:
    def nsset__cmp__(self, other):
        raise TypeError("Cannot compare sets using cmp")

def nsset__length_hint__(self):
    return len(self)

def nsset_update(self, *others):
    for other in others:
        if isinstance(other, Set):
            self.unionSet_(other)
        else:
            self.unionSet_(set(other))

def nsset_intersection_update(self, *others):
    for other in others:
        if isinstance(other, Set):
            self.intersectSet_(other)
        else:
            self.intersectSet_(set(other))

def nsset_difference_update(self, *others):
    for other in others:
        if isinstance(other, Set):
            self.minusSet_(other)
        else:
            self.minusSet_(set(other))

def nsset_symmetric_difference_update(self, other):
    toadd = set()
    toremove = set()

    if isinstance(other, Set):
        totest = other
    else:
        totest = set(other)

    for value in self:
        if value in totest:
            toremove.add(value)
    for value in totest:
        if value not in self:
            toadd.add(value)

    self.minusSet_(toremove)
    self.unionSet_(toadd)

def nsset_pop(self):
    if len(self) == 0:
        raise KeyError()

    v = self.anyObject()
    self.removeObject_(v)
    return container_unwrap(v, KeyError)

def nsset_remove(self, value):
    hash(value)
    value = container_wrap(value)
    if value not in self:
        raise KeyError(value)
    self.removeObject_(value)

def nsset_discard(self, value):
    hash(value)
    self.removeObject_(container_wrap(value))

def nsset_add(self, value):
    hash(value)
    self.addObject_(container_wrap(value))

class nsset__iter__ (object):
    def __init__(self, value):
        self._size = len(value)
        self._enum = value.objectEnumerator()

    def __length_hint__(self):
        return self._size

    def __iter__(self):
        return self

    def __next__(self):
        self._size -= 1
        return container_unwrap(self._enum.nextObject(), StopIteration)

    next = __next__




CLASS_METHODS['NSSet'] = (
    ('__iter__', lambda self: nsset__iter__(self)),
    ('__length_hint__', nsset__length_hint__),
    ('__contains__',  nsset__contains__),
    ('isdisjoint',  nsset_isdisjoint),
    ('union',  nsset_union),
    ('intersection',  nsset_intersection),
    ('difference',  nsset_difference),
    ('symmetric_difference',  nsset_symmetric_difference),
    ('issubset', nsset_issubset),
    ('__eq__', nsset__eq__),
    ('__ne__', nsset__ne__),
    ('__le__', nsset__le__),
    ('__lt__', nsset__lt__),
    ('issuperset', nsset_issuperset),
    ('__ge__', nsset__ge__),
    ('__gt__', nsset__gt__),
    ('__or__', nsset__or__),
    ('__ror__', nsset__ror__),
    ('__and__', nsset__and__),
    ('__rand__', nsset__rand__),
    ('__xor__', nsset__xor__),
    ('__rxor__', nsset__xor__),
    ('__sub__', nsset__sub__),
)

if sys.version_info[0] == 2:
    CLASS_METHODS['NSSet'] += (
        ('__cmp__', nsset__cmp__),
    )

CLASS_METHODS['NSMutableSet'] = (
    ('add',  nsset_add),
    ('remove',  nsset_remove),
    ('discard',  nsset_discard),
    ('update', nsset_update),
    ('intersection_update', nsset_intersection_update),
    ('difference_update', nsset_difference_update),
    ('symmetric_difference_update', nsset_symmetric_difference_update),
    ('clear', lambda self: self.removeAllObjects()),
    ('pop', nsset_pop),
)

def nsset_new(cls, sequence=None):
    if not sequence:
        return NSSet.set()

    if isinstance(sequence, (NSSet, set, frozenset)):
        return NSSet.set().setByAddingObjectsFromSet_(sequence)

    else:
        return NSSet.set().setByAddingObjectsFromSet_(set(sequence))

def nsmutableset_new(cls, sequence=None):
    if not sequence:
        value = NSMutableSet.set()

    elif isinstance(sequence, (NSSet, set, frozenset)):
        value = NSMutableSet.set()
        value.unionSet_(sequence)

    else:
        value = NSMutableSet.set()
        value.unionSet_(set(sequence))

    return value

NSSet.__new__ = nsset_new
NSMutableSet.__new__ = nsmutableset_new

NSMutableSet.alloc().init()