ios developer tiny share-20160822

来源:互联网 发布:js object empty 编辑:程序博客网 时间:2024/06/14 05:32

今天讲Objective-C的NSObject的两个方法,alloc和init。

Objects Are Created Dynamically

As described earlier in this chapter, memory is allocated dynamically for an Objective-C object. The first step in creating an object is to make sure enough memory is allocated not only for the properties defined by an object’s class, but also the properties defined on each of the superclasses in its inheritance chain.

The NSObject root class provides a class method, alloc, which handles this process for you:

+ (id)alloc;

Notice that the return type of this method is id. This is a special keyword used in Objective-C to mean “some kind of object.” It is a pointer to an object, like (NSObject *), but is special in that it doesn’t use an asterisk. It’s described in more detail later in this chapter, in Objective-C Is a Dynamic Language.

The alloc method has one other important task, which is to clear out the memory allocated for the object’s properties by setting them to zero. This avoids the usual problem of memory containing garbage from whatever was stored before, but is not enough to initialize an object completely.

You need to combine a call to alloc with a call to init, another NSObject method:

- (id)init;

The init method is used by a class to make sure its properties have suitable initial values at creation, and is covered in more detail in the next chapter.

Note that init also returns an id.

If one method returns an object pointer, it’s possible to nest the call to that method as the receiver in a call to another method, thereby combining multiple message calls in one statement. The correct way to allocate and initialize an object is to nest the alloc call inside the call to init, like this:

NSObject *newObject = [[NSObject alloc] init];

This example sets the newObject variable to point to a newly created NSObject instance.

The innermost call is carried out first, so the NSObject class is sent the alloc method, which returns a newly allocated NSObject instance. This returned object is then used as the receiver of the init message, which itself returns the object back to be assigned to the newObject pointer, as shown in Figure 2-5.

Figure 2-5  Nesting the alloc and init message


Note: It’s possible for init to return a different object than was created by alloc, so it’s best practice to nest the calls as shown.
Never initialize an object without reassigning any pointer to that object. As an example, don’t do this:
 

NSObject *someObject = [NSObject alloc];[someObject init];

If the call to init returns some other object, you’ll be left with a pointer to the object that was originally allocated but never initialized.

0 0
原创粉丝点击