-1

I'm new to Objective-C and I'm finding the syntax of valid Objective-C code hard to understand. For example, all objects are normally allocated and initialized using the MyClass *myObject = [[MyClass alloc] init]; syntax. However, in the example below, a method is called on the "NSKeyedArchiver" class before creating an initialized object of that class. The same situation happens in the next line of code, where a method is called on "NSUserDefaults" without creating an allocated/initialized object. How is this possible?

NSData *bandObjectData = [NSKeyedArchiver archivedDataWithRootObject:self.bandObject];
[[NSUserDefaults standardUserDefaults] setObject:bandObjectData forKey:bandObjectKey];

Thanks!

1 Answers1

1

These are called class methods and they don't require an instance of a class to be performed because they don't depend on an actual class instance. You can actually create your own by prefacing the method with a + sign (as opposed to a - sign)

We generally use class methods when we don't depend on an instance of a class. So in your examples, the NSKeyedArchiver class doesn't need an instance of itself to be created in order to archive data. Similarly, you can get the standard NSUserDefaults without having a NSUserDefaults object created.

The other types of methods (instance methods) are used when the object itself needs to change its state.

Choppin Broccoli
  • 3,048
  • 2
  • 21
  • 28