public function offsetSet($offset, $value)
    {
        if (
            $this->row_wrapper_class !== null &&
            !($value instanceof $this->row_wrapper_class)
        ) {
            throw new UnexpectedValueException(
                sprintf(
                    'Value should be an instance of %s.',
                    $this->row_wrapper_class
                )
            );
        }

        if ($offset === null) {
            // add
            $this->objects[] = $value;

            // if index field is set, index the object
            if (
                $this->index_field !== null &&
                isset($value->{$this->index_field})
            ) {
                if ($value->hasInternalValue($this->index_field)) {
                    $index = $value->getInternalValue($this->index_field);
                } else {
                    $index = $value->{$this->index_field};
                }
                $this->objects_by_index[$index] = $value;
            }
        } else {
            // replace at offset
            if (!isset($this[$offset])) {
                throw new OutOfBoundsException(
                    sprintf(
                        'No record to replace exists at offset %s.',
                        $offset
                    )
                );
            }

            if ($this->index_field === null) {
                $this->removed_objects[] = $this->objects[$offset];
                $this->objects[$offset] = $value;
            } else {
                $index_field = $this->index_field;

                // update object index field value
                $value->$index_field = $offset;

                // find and replace ordinally indexed objects
                foreach ($this->objects as $key => $object) {
                    if ($object->$index_field === $value->$index_field) {
                        $this->removed_objects[] = $object;
                        $this->objects[$key] = $value;
                    }
                }

                // add object to indexed array
                $this->objects_by_index[$offset] = $value;
            }
        }

        // only set the db on added object if it is set for this recordset
        if ($this->db !== null && $value instanceof SwatDBRecordable) {
            $value->setDatabase($this->db);
        }

        // Remove object from removed list if it was on list of removed
        // objects. This step needs to happen after adding the new record
        // for the case where we replaced an object with itself.
        $keys = array_keys($this->removed_objects, $value, true);
        foreach ($keys as $key) {
            unset($this->removed_objects[$key]);
        }
    }