[Pythonmac-SIG] strange behavior with NSArray and python unicode types

Ronald Oussoren ronaldoussoren at mac.com
Mon Aug 15 19:25:34 CEST 2005


On 15-aug-2005, at 18:59, Jon Rosebaugh wrote:

> On 8/14/05, Ronald Oussoren wrote:
>
>> On 13-aug-2005, at 10:52, Jon Rosebaugh wrote:
>>
>>> You're right, it wasn't the problem; I'm kinda ashamed that I didn't
>>> notice it now, because the self.Name was a unicode string too,  
>>> and it
>>> worked fine. Turns out that self.Data was a objc.pyobjc_unicode
>>> object, since it had gone through the bridge and back. Sorry to
>>> trouble you.
>>>
>>
>> That still sounds fishy. If I understand you correctly you have a
>> pyobjc_unicode object that is not an empty string (that is
>> "theString != ''"), but is an empty string when converted back to
>> Objective-C. Could you elaborate on what you're doing? Unless the
>> Objective-C strings is an NSMutableString and someone is mutating it
>> behind your back the value in python should be the same as the value
>> in ObjC.
>>
>
> Yeah. um. Basically, the pyobjc_unicode object is not an empty string.
> (I get this object by calling editor.string(), where editor is a
> NSTextView instance.) But when I try to feed it into a NSMutableArray
> via addObject:, the resulting array has an empty string where the
> pyobjc_unicode's contents should be.
>
> However, if I feed unicode(self.Data) into the NSMutableArray, it
> contains the string it should.

NSTextView.string (or rather NSText.string) returns a reference to  
the backing store of the view. Given:

     aTextView = <some NSTextView>
     body = aTextView.string()
     aTextView.selectAll_(None)
     aTextView.delete_(None)

At the end of this block body is pointing to an empty  
NSMutableString. However, the python value of the string is whatever  
was in the textview at the call to aTextView.string. This is one  
point where the bridge is showing true: python's unicode and  
pyobjc_unicode are immutable types (necessary to make it possible to  
use them as dict keys), while NSMutableString is (obviously) mutable.  
The sad result is that pyobjc_unicode instances don't reflect changes  
in the underlying NSMutableString.

The best workaround is to copy the string when dealing with mutable  
strings and you don't want to see the changes (e.g. use unicode 
(aTextView.string())), or to get a direct reference to the  
NSMutableString when you do want to see updates (use aTextView.string 
().nsstring()) and explicitly convert the string to unicode whenever  
you need to pass the value to a normal python API).

Ronald

>
> Moreover, when I create a tiny demo of the problem, it actually works
> fine, which means I probably have crufty code somewhere. Hate it when
> that happens.
> _______________________________________________
> Pythonmac-SIG maillist  -  Pythonmac-SIG at python.org
> http://mail.python.org/mailman/listinfo/pythonmac-sig
>



More information about the Pythonmac-SIG mailing list