ios developer tiny share-20160824

前面几节,我们讲了创建对象的方法,包括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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值