NSArray LastObject

Discussion in 'iOS Programming' started by larswik, Nov 4, 2012.

  1. larswik macrumors 68000

    Joined:
    Sep 8, 2006
    #1
    Hey quick question. I have a plist that I am unpacking to add an object and re save.

    Code:
     NSMutableArray *exerArray = [[NSMutableArray alloc] initWithContentsOfFile:[bpc returnPath:@"exerciseLog.plist"]];
        NSMutableDictionary *exerDict = [NSMutableDictionary dictionaryWithDictionary:[exerArray lastObject]];
        [exerDict setValue: totalCalLabel.text forKey: itemNameTextField.text];
    
    
    It's the objects I need will always be at the last index so I can use "LastObject" Task from the Array class to perform that. But when I add an object to a dict and want to replace the dict that is saved at the last index of the Array I need the index number to replace that index.

    The way I have been doing it is to just get the count of the Array then -1 to find the last index to write to. I was just wondering if anyone new a short cut that I can write to the lastObject just as easy as I retrieve from it.

    I am not stuck and my method works just fine, I was just wondering?

    Thanks
     
  2. Reason077 macrumors 68000

    Reason077

    Joined:
    Aug 14, 2007
    #2
    This is perfectly correct. lastObject is just a shortcut for "objectAtIndex: ([array count] - 1)".
     
  3. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #3
    Thanks Reason0777, I am always looking for little short cuts in code when possible. Since I saw the "lastObject" it got me wondering if there was the opposite of that.

    It seems like Apple should make a change to "lastObject" and make Task that is "lastIndex" instead. This would allow you to read or replace to the last index of an array.

    But thanks, I was just wondering!
     
  4. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #4
    replaceObject:atIndex: should do what you want. If you want something like replaceLastObjectWithObject: you can easily add that with a category.
     
  5. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #5
    Yep, that is how I am currently replacing it. I have read about Categories but I have never used them. Might be a good learning experience for that. replaceObject:atIndex: required knowing the index number. Where as retrieving the last object you do not need the index number. If you could do lastObject.count in [myArray replaceObject: newObject atIndex: lastObject.count]; , although you can't of course.

    It is just speculation and I don't mean to start a discussion on the subject. But I think learning / implementing categories could be a fun project for tonight.

    Thanks again!
     

Share This Page