<!--
{
  "availability" : [
    "iOS: -",
    "iPadOS: -",
    "macCatalyst: -",
    "macOS: -",
    "tvOS: -",
    "visionOS: -",
    "watchOS: -"
  ],
  "documentType" : "symbol",
  "framework" : "ObjectiveC",
  "identifier" : "/documentation/ObjectiveC/NSObject-swift.class/setValue(_:forKey:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Objective-C Runtime",
      "ObjectiveC"
    ],
    "preciseIdentifier" : "c:objc(cs)NSObject(im)setValue:forKey:"
  },
  "title" : "setValue(_:forKey:)"
}
-->

# setValue(_:forKey:)

Sets the property of the receiver specified by a given key to a given value.

```
func setValue(_ value: Any?, forKey key: String)
```

## Parameters

`value`

The value for the property identified by `key`.

`key`

The name of one of the receiver’s properties.

## Discussion

If `key` identifies a to-one relationship, relate the object specified by `value` to the receiver, unrelating the previously related object if there was one. Given a collection object and a `key` that identifies a to-many relationship, relate the objects contained in the collection to the receiver, unrelating previously related objects if there were any.

The search pattern that `setValue:forKey:` uses is described in [Accessor Search Patterns](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueCoding/SearchImplementation.html#//apple_ref/doc/uid/20000955) in [Key-Value Coding Programming Guide](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueCoding/index.html#//apple_ref/doc/uid/10000107i).

In a reference-counted environment, if the instance variable is accessed directly, `value` is retained.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)