当我尝试将NSDictionary添加到NSMutableArray中时,我无法替换最后添加的对象

时间:2019-03-27 04:51:36

标签: objective-c xcode nsmutablearray nsmutabledictionary

我需要将NSDictionary添加到NSMutableArray中。

首先,我用其他结构的键值创建了一个NSMutableDictionary

for (NSString *key in selectedFiltersByUser) {
    [filters_data setObject:key forKey:@"key"];
    [filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];

    // Added filter selected id's into Array for all query_params
    [query_params addObject:filters_data];
}

selectedFiltersByUser是这样的字典:

{
category_id = "XXX";
sort = "last_updated_asc";
status = "rejected_by_seller";
}

,并为该字典中的每个key:value创建一个新的NSMutableDictionary,如下所示:

{
  key: category_id,
  value: XXX
}

这个新的NSMutableDictionary像这样添加到NSMutableArray中:

    for (NSString *key in selectedFiltersByUser) {
    [filters_data setObject:key forKey:@"key"];
    [filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];

    // Added filter selected id's into Array for all query_params
    [query_params addObject:filters_data];
}

但是当将此NSMutableDictionary添加到NSMutableArray时,它不会替换最后一个对象,而我在query_params中得到了它:

    {
       key: category_id,
       value: XXX
   },
   {
    key: category_id,
    value: XXX
   },
   {
    key: category_id,
    value: XXX
   }

我需要这个:

{
       key: category_id,
       value: XXX
   },
   {
    key: sort,
    value: last_updated_asc
   },
   {
    key: status,
    value: rejected_by_seller
   }

我不知道如何替换最后添加的对象。

3 个答案:

答案 0 :(得分:1)

尝试在for循环中[NSMutableDictionary alloc] init],然后添加数据。

因为当您init跳出循环时,每次它都将进入内部循环且键相同,因此它将被新值覆盖。如果您init进入循环,则会创建一个新的循环。

for (NSString *key in selectedFiltersByUser) {

    //INIT HERE YOUR DICTIONARY
    NSMutableDictionary *filters_data = [NSMutableDictionary alloc] init];

    [filters_data setObject:key forKey:@"key"];
    [filters_data setObject:selectedFiltersByUser[key] forKey:@"value"];

    // Added filter selected id's into Array for all query_params
    [query_params addObject:filters_data];
}

答案 1 :(得分:0)

向该数组添加字典不会复制该字典。它将对对象(字典)的引用存储到数组,因此每次都添加对相同字典的引用。

覆盖字典的内容会更改相同的字典,该字典将多次存储在数组中。

您每次都必须创建一个新词典。没有理由创建一个可变的。

答案 2 :(得分:0)

正如评论所指出的那样,您的问题是由于Objective-C集合的引用语义引起的,即它们包含对现有对象的引用和它们的 not 副本。因此,如果您在代码中向class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) createNotificationChannel() notification() } private fun createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val importance = NotificationManager.IMPORTANCE_HIGH val channel = NotificationChannel("ID", "name", importance).apply { description = "description" lockscreenVisibility = Notification.VISIBILITY_PUBLIC } val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } } private fun notification() { val KEY_TEXT_REPLY = "key_text_reply" val replyLabel: String = "replyLabel" var remoteInput: RemoteInput = RemoteInput.Builder(KEY_TEXT_REPLY).run { setLabel(replyLabel) build() } var replyPendingIntent: PendingIntent = PendingIntent.getBroadcast(applicationContext, 1, Intent(), PendingIntent.FLAG_UPDATE_CURRENT) var action: NotificationCompat.Action = NotificationCompat.Action.Builder( 0, "label", replyPendingIntent ).addRemoteInput(remoteInput) .build() val newMessageNotification = NotificationCompat.Builder(this, "ID") .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("title") .setContentText("content text") .addAction(action) .setPriority(NotificationCompat.PRIORITY_MAX) .setDefaults(NotificationCompat.DEFAULT_ALL) .setCategory(NotificationCompat.CATEGORY_STATUS) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setOngoing() .build() with(NotificationManagerCompat.from(this)) { notify(1, newMessageNotification) } } 多次添加相同的NSMutableDictionary,那么最终数组的每个元素都是对 same 字典的引用。已经建议的简单解决方法是在循环中分配字典:

NSMutableArray

但是,您可以使其更简单并完全避免该问题。您已经为for (NSString *key in selectedFiltersByUser) { NSMutableDictionary *filters_date = [NSMutableDictionary new]; [filters_data setObject:key forKey:@"key"]; [filters_data setObject:selectedFiltersByUser[key] forKey:@"value"]; [query_params addObject:filters_data]; } 编制了索引,也可以通过类似的方式为selectedFiltersByUser编制索引,为您提供:

filters_data

但是仍然剩下分配,您可以使用字典文字将其删除:

for (NSString *key in selectedFiltersByUser)
{
   NSMutableDictionary *filters_date = [NSMutableDictionary new];
   filters_data[@"key"] = key;
   filters_data[@"value"] = selectedFiltersByUser[key];
   [query_params addObject:filters_data];
}

现在,分配由编译器自动处理,您将得到for (NSString *key in selectedFiltersByUser) { NSDictionary *filters_date = @{ @"key": key, @"value": selectedFiltersByUser[key] }; [query_params addObject:filters_data]; } 。最后一个选择是完全删除NSDictionary

filters_date

您可能会发现使用字典(和数组)文字可以帮助您避免分配错误,并在不需要它们时创建可变结构。 HTH