NSMutableArray as a Property - addObject: is an unrecognized selector?

Discussion in 'iOS Programming' started by ArtOfWarfare, Sep 1, 2011.

  1. ArtOfWarfare, Sep 1, 2011
    Last edited: Sep 1, 2011

    ArtOfWarfare macrumors 604

    ArtOfWarfare

    Joined:
    Nov 26, 2007
    #1
    In my header file I declare this property:
    Code:
    @property (readwrite, retain) NSMutableArray *clippings;
    The synthesizer is in the main file:
    Code:
    @synthesize clippings;
    And here's the code where it crashes:
    Code:
    - (void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
    
        NSString *clipPath = [[NSBundle mainBundle] pathForResource:@"Clippings" ofType:@"txt"];
        NSString *clipString = [NSString stringWithContentsOfFile:clipPath encoding:NSUTF16BigEndianStringEncoding error:NULL];
        self.clippings = (NSMutableArray *)[clipString componentsSeparatedByString:@"\n"];
        
        if (![self.clippings containsObject:[UIPasteboard generalPasteboard].string])
        {
            [color="RED"][self.clippings addObject:[UIPasteboard generalPasteboard].string];[/color]
        }
    }
    The line in red gets highlighted and in the crash log it says:
    I declared it as a NSMutableArray, I set up the property to be read-write, and I cast it as a mutable array when I set it. I can't imagine what else I could do to try to make it accept [addObject] besides having an inelegant work around of copying my array's contents into a new array with a new object added in.

    Many thanks to anyone who can offer some help with this.
     
  2. hayesk macrumors 65816

    Joined:
    May 20, 2003
    #2
    Your line
    Self.clippings = (NSMutabkeArray*)[clippings
    Was cut off but that's likely the problem. It doesn't matter if you cast it as NSMutableArray or not. If that method (the one cut off in your post) doesn't return an NSMutabkeArray, then it won't work. Casting only fools it into thinking the object is of another class, it doesn't actually change the object. The casting only made the code compile, but it doesn't magically make an array mutable. That's why it crashed when you tried to make it do something it couldn't do.

    You'll have to make sure that method returns a mutable array or make a mutable copy. (don't forget to autorelease the copy)
     
  3. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #3
    The blue-hilited code gives an NSArray. It does not give an NSMutableArray.

    The type-cast to NSMutableArray is meaningless. You can't make a cow fly simply by naming it "Tweetybird" or "Cessna". You can't change the fundamental nature of an object just by lying about its type.

    You need to get a NSMutableArray from an NSArray. -mutableCopy is one such. There are others.
     

Share This Page