Class: NSUserDefaults

Inherits:
Object
  • Object
show all
Defined in:
lib/bean/nsuserdefaults_additions.rb

Overview

Extensions to the NSUserDefaults class

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.[](key) ⇒ Object

Shortcut for retrieving a key from the standardUserDefaults

Examples:

NSUserDefaults[:foo]

Parameters:

  • key (String|Symbol)

    The key to retrieve

Returns:

  • (Object)

    The value for the given key



24
25
26
# File 'lib/bean/nsuserdefaults_additions.rb', line 24

def self.[](key)
  standardUserDefaults[key]
end

.[]=(key, value) ⇒ Nil

Shortcut for setting a key/value into the standardUserDefaults

Examples:

NSUserDefaults[:foo] = 'bar'

Parameters:

  • key (String|Symbol)

    The key to set

  • value (Object)

    The object to set

Returns:

  • (Nil)


12
13
14
# File 'lib/bean/nsuserdefaults_additions.rb', line 12

def self.[]=(key, value)
  standardUserDefaults[key] = value
end

Instance Method Details

#[](key) ⇒ Object

Note:

I'm not using the standard MacRuby sugaring here as I need to to_s the key. Keeps everything constent.

Helper method for retrieving an object from the defaults

Parameters:

  • key (String|Symbol)

    The key to retrieve

Returns:

  • (Object)

    The value for the given key



68
69
70
# File 'lib/bean/nsuserdefaults_additions.rb', line 68

def [](key)
  objectForKey(key.to_s)
end

#[]=(key, value) ⇒ Nil

Helper method for setting data into the user defaults

If the value is provided, the given key will be set. If the value is nil the given key will be deleted.

This method always synchronizes the defaults.

Parameters:

  • key (String|Symbol)

    The key to set or delete

  • value (Object|Nil)

    The value to set

Returns:

  • (Nil)


51
52
53
54
55
56
57
58
# File 'lib/bean/nsuserdefaults_additions.rb', line 51

def []=(key, value)
  if value
    setObject(value, forKey:key.to_s)
  else
    delete(key.to_s)
  end
  sync
end

#delete(key) ⇒ Nil

Helper to remove an object from the defaults.

This method always synchronizes the defaults.

Parameters:

  • key (String|Symbol)

    The key to remove.

Returns:

  • (Nil)


36
37
38
# File 'lib/bean/nsuserdefaults_additions.rb', line 36

def delete(key)
  standardUserDefaults.delete(key)
end