NSConcreteAttributedString mutableString crash

Discussion in 'Mac Programming' started by mdeh, Mar 14, 2010.

  1. mdeh macrumors 6502

    Joined:
    Jan 3, 2009
    #1
    Hi all,
    I have a problem that I cannot understand! :confused:

    According to the documentation, there is a method "mutableString" which, in the NSMutableAttributedString class
    So, with this code

    Code:
    NSMutableString * s = [_mString mutableString];
    I would have expected s to be a mutableString. Here is the error:

    Changing to this code:

    Code:
    NSString * s = [_mString string];
    eliminates this issue...but the question is why? The literature that I have looked at does not seem to have an answer.

    Thanks as usual.
     
  2. kainjow Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #2
    NSMutableAttributedString's methods aren't inherited by NSAttributedString. So any method specifically defined for NSMutableAttributedString will not work on NSAttributedString.

    If you want a mutable string for NSAttributedString just call mutableCopy on the string.

    How is _mString created?
     
  3. mdeh thread starter macrumors 6502

    Joined:
    Jan 3, 2009
    #3
    Kainjow...thanks, first off.

    -mString is created by by taking the textStorage property of an NSTextView, and setting an NSMutableAttributed string using an accessor thus.


    Code:
    -(void) setMString:(NSMutableAttributedString *) m
    {
    	if ( m == nil)
    	{
    		return;
    	}
    	m = [m copy];
    	[_mString release];
    	_mString = m;
    Earlier, I removed the actual use of the setter to make it read more easily, but here is the actual call to set it.

    Code:
    [[self cypherCenter] setMString:[[self cypherField]textStorage]];
    Where cypherCenter is the class that has the accessor setMString.


    Where I am a little confused is that the method:
    - (NSMutableString *)mutableString is described within the NSMutableAttributedString Class and shows that an NSMutableString is returned, which is what I thought I was doing :), but apparently not! Well, it was causing this issue. Still a little confused, but thanks for your input.
     
  4. kainjow Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #4
    Code:
    m = [m copy];
    Try using mutableCopy here.

    Have a read through the section Copying Mutable Versus Immutable Objects (at the bottom). Basically, if you call copy on a mutable object, it will return an immutable one instead. This applies to things like NSArray, NSString, NSDictionary, etc., and other classes that have a separate mutable version.
     
  5. mdeh thread starter macrumors 6502

    Joined:
    Jan 3, 2009
    #5
    Now I have!! :)

    That's clearly what's going on.
    Thanks again.
     

Share This Page