前面几节,我们讲了创建对象的方法,包括alloc、init、initWithXX、工厂方法,今天我们讲使用new来创建对象,另外,会讲试用“@”来创建literal类型的对象。
Use new to Create an Object If No Arguments Are Needed for Initialization
It’s also possible to create an instance of a class using the new class method. This method is provided by NSObject and doesn’t need to be overridden in your own subclasses.
It’s effectively the same as calling alloc and init with no arguments:
XYZObject *object = [XYZObject new];
// is effectively the same as:
XYZObject *object = [[XYZObject alloc] init];
Literals Offer a Concise Object-Creation Syntax
Some classes allow you to use a more concise, literal syntax to create instances.
You can create an NSString instance, for example, using a special literal notation, like this:
NSString *someString = @"Hello, World!";
This is effectively the same as allocating and initializing an NSString or using one of its class factory methods:
NSString *someString = [NSString stringWithCString:"Hello, World!"
encoding:NSUTF8StringEncoding];
The NSNumber class also allows a variety of literals:
NSNumber *myBOOL = @YES;
NSNumber *myFloat = @3.14f;
NSNumber *myInt = @42;
NSNumber *myLong = @42L;
Again, each of these examples is effectively the same as using the relevant initializer or a class factory method.
You can also create an NSNumber using a boxed expression, like this:
NSNumber *myInt = @(84 / 2);
In this case, the expression is evaluated, and an NSNumber instance created with the result.
Objective-C also supports literals to create immutable NSArray and NSDictionary objects; these are discussed further in Values and Collections.