开发者

id dynamic type documentation

Can someo开发者_JAVA百科ne point me to the specific "id type documentation" ? I've been through the dynamic typing docs, but I want to know how to use the type id. Specifically how to check if id is null.


The id type is directly related to the Objective-C language itself, rather than the Cocoa/Cocoa Touch frameworks as your original tags implied. There is also no dynamic typing involved. Here's a little introduction in Apple's docs.

To answer your specific question, quoted from the above link:

The keyword nil is defined as a null object, an id with a value of 0. id, nil, and the other basic types of Objective-C are defined in the header file objc/objc.h.

nil and NULL are equivalent (zero pointers), and therefore interchangeable.

In a basic if statement, you just do this:

id myId = [[something alloc] init];

// Short for if (myId == nil)
if (!myId) {
    // myId is nil
} else {
    // myId is not nil
}


See The Objective-C Programming Language — specifically, the chapter on Objects, Classes and Messaging.

In Objective-C, object identifiers are of a distinct data type: id. This type is the general type for any kind of object regardless of class and can be used for instances of a class and for class objects themselves. […]

The keyword nil is defined as a null object, an id with a value of 0. id, nil, and the other basic types of Objective-C are defined in the header file objc/objc.h.

To compare variables by value, you simply use the == operator. So to test for nil, you do:

 someVariable == nil


I've not seen it clearly stated in any other answers so I'll say it here:

an id is defined as a pointer to an object.

nil is zero cast as an id - (id)0 - as a result the following code:

NSString * myString = nil;
id idString = myString;
if (idString == nil) NSLog(@"idString == nil");
if (idString == NULL) NSLog(@"idString == NULL");
if (idString == (id)0) NSLog(@"idString == (id)0");

will have the following output:

2011-09-12 07:25:57.297 Sample Project[22130:707] idString == nil
2011-09-12 07:25:57.298 Sample Project[22130:707] idString == NULL
2011-09-12 07:25:57.299 Sample Project[22130:707] idString == (id)0


Sorry if I misunderstood your question, but wouldn't you just do something like:

// given
id sender;

if (sender == nil) {}

Basically you use id to catch any object that might be assigned to it. So you can do something like:

id name = [NSString stringWithString:@"john"];

and now name will be an NSString object, which you can verify by calling [name class].

Take a look at the id section of this page for more information.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜