replaceObjectAtIndex nsmutableArray - PullRequest
       3

replaceObjectAtIndex nsmutableArray

0 голосов
/ 06 марта 2012

РЕДАКТИРОВАТЬ: это мой полный код:

У меня есть массив, как выглядит так:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <dict>
        <key>destinataire</key>
        <string>david</string>
        <key>expediteur</key>
        <string>sophie</string>
        <key>idMessage</key>
        <string>1729</string>
        <key>message</key>
        <string>ok a plus</string>
        <key>photoExp</key>
        <string>http://photos/hbrJUlrTgj.jpg</string>
        <key>statusE</key>
        <string>1</string>
    </dict>
    <dict>
        <key>destinataire</key>
        <string>david</string>
        <key>expediteur</key>
        <string>max</string>
        <key>idMessage</key>
        <string>1730</string>
        <key>message</key>
        <string>ok a plus</string>
        <key>photoExp</key>
        <string>http:///photos/4xlWoAHT8b.jpg</string>
        <key>statusE</key>
        <string>1</string>
    </dict>
    <dict>
        <key>destinataire</key>
        <string>david</string>
        <key>expediteur</key>
        <string>michel</string>
        <key>idMessage</key>
        <string>1731</string>
        <key>message</key>
        <string>ok a plus</string>
        <key>photoExp</key>
        <string>http:///photos/TR7oO6O8Z8.jpg</string>
        <key>statusE</key>
        <string>1</string>
    </dict>
</array>
</plist>

Мне нужно поместить новые данные в этот массив, но в моих новых данных у меня есть это:

<dict>
            <key>destinataire</key>
            <string>david</string>
            <key>expediteur</key>
            <string>sophie</string>
            <key>idMessage</key>
            <string>1729</string>
            <key>message</key>
            <string>ok a plus</string>
            <key>photoExp</key>
            <string>http://photos/hbrJUlrTgj.jpg</string>
            <key>statusE</key>
            <string>1</string>
        </dict>

Софи уже существует в моем массиве, поэтому мне нужно найти индекс в моем массиве, где Софи, как представляется, помещает мои новые данные

так что я делаю это, чтобы попытаться найти дубликаты данных и заменить их

if ([[allMessageArray valueForKey:@"expediteur"]containsObject:[dicoChat2 objectForKey:@"expediteur"]] ) 
    {
    for( int i=0;i<[allMessageArray count];i++)
      {
    NSDictionary *dicoChat22 = [allMessageArray objectAtIndex:i];

    NSMutableDictionary *  datas2= [[NSMutableDictionary alloc]init];

    [datas2 setObject:[dicoChat22 objectForKey:@"destinataire"] forKey:@"destinataire"];
    [datas2 setObject:[dicoChat22 objectForKey:@"expediteur"] forKey:@"expediteur"];
    [datas2 setObject:[dicoChat22 objectForKey:@"photoExp"] forKey:@"photoExp"];
    [datas2 setObject:[dicoChat22 objectForKey:@"statusE"] forKey:@"statusE"];
    [datas2 setObject:[dicoChat22 objectForKey:@"idMessage"] forKey:@"idMessage"];

    [allMessageArray replaceObjectAtIndex:i withObject:datas2];
    [allMessageArray writeToFile:datAllString atomically:YES];
     }

    }

когда я пытаюсь использовать replaceObjectAtindex: он работает, но все мои данные заменены в каждом индексе. так что я знаю, что не нашел хорошего индекса как я могу это найти?

ТНХ

1 Ответ

1 голос
/ 06 марта 2012

Я не очень хорошо понимаю, что вы пытаетесь сделать, но вот возможное решение (если ваш allMessageArray действительно массив, потому что вы используете valueForKey: with it !!!):

// Browse all messages (you can use "for (NSDictionary *message in allMessageArray)" enumerate loop but because we need the index to replace object, it's the best way to do that)
for (int index = 0; index < allMessageArray.count; ++index) {
  // Get current message dictionary
  NSDictionary *message = [allMessageArray objectAtIndex:index];

  // If message came from good sender (you can use isEqualToString: if both objects are NSString instance)
  if ([[message objectForKey:@"expediteur"] isEqual:[dicoChat2 objectForKey:@"expediteur"]]) {
    // Create an autoreleased mutable copy of message array to modify some data
    NSMutableDictionary *messageModified = [NSMutableDictionary dictionaryWithDictionary:message];

    // *** Modify what you want in messageModified dictionary ***

    // Replace original message with modified message in array (assume that allMessageArray is a mutable array) (It's very bad to modify an array in its enumerate loop but because we don't remove/add an object to the array, it's fine to do like that)
    [allMessageArray replaceObjectAtIndex:index withObject:messageModified];

    // *** If you know that you will have always only one message in array with good sender, you can break the loop here ***
  }
}

// Write array to file
[allMessageArray writeToFile:datAllString atomically:YES];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...