Beispiel #1
0
    def test_class_properties(self):
        "A Python class can have ObjC properties with synthesized getters and setters."

        NSURL = ObjCClass('NSURL')

        class URLBox(NSObject):

            # takes no type: All properties are pointers
            url = objc_property()
            data = objc_property()

            @objc_method
            def getSchemeIfPresent(self):
                if self.url is not None:
                    return self.url.scheme
                return None

        box = URLBox.alloc().init()

        # Default property value is None
        self.assertIsNone(box.url)

        # Assign an object via synthesized property setter and call method that uses synthesized property getter
        url = NSURL.alloc().initWithString_('https://www.google.com')
        box.url = url
        self.assertEqual(box.getSchemeIfPresent(), 'https')

        # Assign None to dealloc property and see if method returns expected None
        box.url = None
        self.assertIsNone(box.getSchemeIfPresent())

        # Try composing URLs using constructors
        base = NSURL.URLWithString('https://pybee.org')
        full = NSURL.URLWithString('contributing/', relativeToURL=base)

        self.assertEqual(
            "Visit %s for details" % full.absoluteURL,
            "Visit https://pybee.org/contributing/ for details"
        )

        # ObjC type conversions are performed on property assignment.
        box.data = "Jabberwock"
        self.assertEqual(box.data, "Jabberwock")

        Example = ObjCClass('Example')
        example = Example.alloc().init()
        box.data = example
        self.assertEqual(box.data, example)

        box.data = None
        self.assertIsNone(box.data)